<commit_before>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "TextureResourceD3D11.h"
#include "RendererD3D11.h"
#include "core/Engine.h"
#include "utils/Log.h"

namespace ouzel
{
    namespace graphics
    {
        static DXGI_FORMAT getD3D11PixelFormat(PixelFormat pixelFormat)
        {
            switch (pixelFormat)
            {
                case PixelFormat::A8_UNORM: return DXGI_FORMAT_A8_UNORM;
                case PixelFormat::R8_UNORM: return DXGI_FORMAT_R8_UNORM;
                case PixelFormat::R8_SNORM: return DXGI_FORMAT_R8_SNORM;
                case PixelFormat::R8_UINT: return DXGI_FORMAT_R8_UINT;
                case PixelFormat::R8_SINT: return DXGI_FORMAT_R8_SINT;
                case PixelFormat::R16_UNORM: return DXGI_FORMAT_R16_UNORM;
                case PixelFormat::R16_SNORM: return DXGI_FORMAT_R16_SNORM;
                case PixelFormat::R16_UINT: return DXGI_FORMAT_R16_UINT;
                case PixelFormat::R16_SINT: return DXGI_FORMAT_R16_SINT;
                case PixelFormat::R16_FLOAT: return DXGI_FORMAT_R16_FLOAT;
                case PixelFormat::R32_UINT: return DXGI_FORMAT_R32_UINT;
                case PixelFormat::R32_SINT: return DXGI_FORMAT_R32_SINT;
                case PixelFormat::R32_FLOAT: return DXGI_FORMAT_R32_FLOAT;
                case PixelFormat::RG8_UNORM: return DXGI_FORMAT_R8G8_UNORM;
                case PixelFormat::RG8_SNORM: return DXGI_FORMAT_R8G8_SNORM;
                case PixelFormat::RG8_UINT: return DXGI_FORMAT_R8G8_UINT;
                case PixelFormat::RG8_SINT: return DXGI_FORMAT_R8G8_SINT;
                case PixelFormat::RGBA8_UNORM: return DXGI_FORMAT_R8G8B8A8_UNORM;
                case PixelFormat::RGBA8_SNORM: return DXGI_FORMAT_R8G8B8A8_SNORM;
                case PixelFormat::RGBA8_UINT: return DXGI_FORMAT_R8G8B8A8_UINT;
                case PixelFormat::RGBA8_SINT: return DXGI_FORMAT_R8G8B8A8_SINT;
                case PixelFormat::RGBA16_UNORM: return DXGI_FORMAT_R16G16B16A16_UNORM;
                case PixelFormat::RGBA16_SNORM: return DXGI_FORMAT_R16G16B16A16_SNORM;
                case PixelFormat::RGBA16_UINT: return DXGI_FORMAT_R16G16B16A16_UINT;
                case PixelFormat::RGBA16_SINT: return DXGI_FORMAT_R16G16B16A16_SINT;
                case PixelFormat::RGBA16_FLOAT: return DXGI_FORMAT_R16G16B16A16_FLOAT;
                case PixelFormat::RGBA32_UINT: return DXGI_FORMAT_R32G32B32A32_UINT;
                case PixelFormat::RGBA32_SINT: return DXGI_FORMAT_R32G32B32A32_SINT;
                case PixelFormat::RGBA32_FLOAT: return DXGI_FORMAT_R32G32B32A32_FLOAT;
                default: return DXGI_FORMAT_UNKNOWN;
            }
        }

        TextureResourceD3D11::TextureResourceD3D11()
        {
        }

        TextureResourceD3D11::~TextureResourceD3D11()
        {
            if (depthStencilTexture)
            {
                depthStencilTexture->Release();
            }

            if (depthStencilView)
            {
                depthStencilView->Release();
            }

            if (renderTargetView)
            {
                renderTargetView->Release();
            }

            if (resourceView)
            {
                resourceView->Release();
            }

            if (texture)
            {
                texture->Release();
            }

            if (samplerState)
            {
                samplerState->Release();
            }

            width = 0;
            height = 0;
        }

        bool TextureResourceD3D11::upload()
        {
            std::lock_guard<std::mutex> lock(uploadMutex);

            if (dirty)
            {
                RendererD3D11* rendererD3D11 = static_cast<RendererD3D11*>(sharedEngine->getRenderer());

                if (dirty & DIRTY_DATA)
                {
                    if (size.v[0] > 0 &&
                        size.v[1] > 0)
                    {
                        if (!texture ||
                            static_cast<UINT>(size.v[0]) != width ||
                            static_cast<UINT>(size.v[1]) != height)
                        {
                            if (texture)
                            {
                                texture->Release();
                            }

                            if (resourceView)
                            {
                                resourceView->Release();
                                resourceView = nullptr;
                            }

                            width = static_cast<UINT>(size.v[0]);
                            height = static_cast<UINT>(size.v[1]);

                            DXGI_FORMAT d3d11PixelFormat = getD3D11PixelFormat(pixelFormat);

                            if (d3d11PixelFormat == DXGI_FORMAT_UNKNOWN)
                            {
                                Log(Log::Level::ERR) << "Invalid pixel format";
                                return false;
                            }

                            D3D11_TEXTURE2D_DESC textureDesc;
                            textureDesc.Width = width;
                            textureDesc.Height = height;
                            textureDesc.MipLevels = (levels.size() > 1) ? 0 : 1;
                            textureDesc.ArraySize = 1;
                            textureDesc.Format = d3d11PixelFormat;
                            textureDesc.Usage = (dynamic && !renderTarget) ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT;
                            textureDesc.CPUAccessFlags = (dynamic && !renderTarget) ? D3D11_CPU_ACCESS_WRITE : 0;
                            textureDesc.SampleDesc.Count = sampleCount;
                            textureDesc.SampleDesc.Quality = 0;
                            textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | (renderTarget ? D3D11_BIND_RENDER_TARGET : 0);
                            textureDesc.MiscFlags = 0;

                            HRESULT hr = rendererD3D11->getDevice()->CreateTexture2D(&textureDesc, nullptr, &texture);
                            if (FAILED(hr))
                            {
                                Log(Log::Level::ERR) << "Failed to create Direct3D 11 texture, error: " << hr;
                                return false;
                            }

                            D3D11_SHADER_RESOURCE_VIEW_DESC resourceViewDesc;
                            resourceViewDesc.Format = d3d11PixelFormat;
                            resourceViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_SRV_DIMENSION_TEXTURE2DMS : D3D11_SRV_DIMENSION_TEXTURE2D;

                            if (sampleCount == 1)
                            {
                                resourceViewDesc.Texture2D.MostDetailedMip = 0;
                                resourceViewDesc.Texture2D.MipLevels = static_cast<UINT>(levels.size());
                            }

                            hr = rendererD3D11->getDevice()->CreateShaderResourceView(texture, &resourceViewDesc, &resourceView);
                            if (FAILED(hr))
                            {
                                Log(Log::Level::ERR) << "Failed to create Direct3D 11 shader resource view, error: " << hr;
                                return false;
                            }

                            if (renderTarget)
                            {
                                if (renderTargetView)
                                {
                                    renderTargetView->Release();
                                }

                                D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
                                renderTargetViewDesc.Format = d3d11PixelFormat;
                                renderTargetViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D;

                                if (sampleCount == 1)
                                {
                                    renderTargetViewDesc.Texture2D.MipSlice = 0;
                                }

                                hr = rendererD3D11->getDevice()->CreateRenderTargetView(texture, &renderTargetViewDesc, &renderTargetView);
                                if (FAILED(hr))
                                {
                                    Log(Log::Level::ERR) << "Failed to create Direct3D 11 render target view, error: " << hr;
                                    return false;
                                }
                            }

                            if (depth)
                            {
                                if (depthStencilTexture)
                                {
                                    depthStencilTexture->Release();
                                }

                                if (depthStencilView)
                                {
                                    depthStencilView->Release();
                                    depthStencilView = nullptr;
                                }

                                D3D11_TEXTURE2D_DESC depthStencilDesc;
                                depthStencilDesc.Width = width;
                                depthStencilDesc.Height = height;
                                depthStencilDesc.MipLevels = 1;
                                depthStencilDesc.ArraySize = 1;
                                depthStencilDesc.Format = DXGI_FORMAT_D32_FLOAT;
                                depthStencilDesc.SampleDesc.Count = sampleCount;
                                depthStencilDesc.SampleDesc.Quality = 0;
                                depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
                                depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
                                depthStencilDesc.CPUAccessFlags = 0;
                                depthStencilDesc.MiscFlags = 0;
                                hr = rendererD3D11->getDevice()->CreateTexture2D(&depthStencilDesc, nullptr, &depthStencilTexture);
                                if (FAILED(hr))
                                {
                                    Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil texture, error: " << hr;
                                    return false;
                                }

                                hr = rendererD3D11->getDevice()->CreateDepthStencilView(depthStencilTexture, nullptr, &depthStencilView);
                                if (FAILED(hr))
                                {
                                    Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil view, error: " << hr;
                                    return false;
                                }
                            }
                        }

                        if (dynamic)
                        {
                            for (size_t level = 0; level < levels.size(); ++level)
                            {
                                if (!levels[level].data.empty())
                                {
                                    D3D11_MAPPED_SUBRESOURCE mappedSubresource;
                                    mappedSubresource.pData = 0;
                                    mappedSubresource.RowPitch = 0;
                                    mappedSubresource.DepthPitch = 0;

                                    HRESULT hr = rendererD3D11->getContext()->Map(texture, static_cast<UINT>(level),
                                                                                (level == 0) ? D3D11_MAP_WRITE_DISCARD : D3D11_MAP_WRITE,
                                                                                0, &mappedSubresource);

                                    if (FAILED(hr))
                                    {
                                        Log(Log::Level::ERR) << "Failed to map Direct3D 11 texture, error: " << hr;
                                        return false;
                                    }

                                    uint8_t* target = reinterpret_cast<uint8_t*>(mappedSubresource.pData);

                                    for (UINT row = 0; row < height; ++row)
                                    {
                                        std::copy(levels[level].data.begin() + row * levels[level].pitch,
                                                  levels[level].data.begin() + (row + 1) * levels[level].pitch,
                                                  target);

                                        target += mappedSubresource.RowPitch;
                                    }

                                    rendererD3D11->getContext()->Unmap(texture, static_cast<UINT>(level));
                                }
                            }
                        }
                        else
                        {
                            for (size_t level = 0; level < levels.size(); ++level)
                            {
                                if (!levels[level].data.empty())
                                {
                                    rendererD3D11->getContext()->UpdateSubresource(texture, static_cast<UINT>(level),
                                                                                nullptr, levels[level].data.data(),
                                                                                static_cast<UINT>(levels[level].pitch), 0);
                                }
                            }
                        }
                    }
                }

                if (dirty & DIRTY_PARAMETERS)
                {
                    clearFrameBufferView = clearColorBuffer;
                    clearDepthBufferView = clearDepthBuffer;

                    frameBufferClearColor[0] = clearColor.normR();
                    frameBufferClearColor[1] = clearColor.normG();
                    frameBufferClearColor[2] = clearColor.normB();
                    frameBufferClearColor[3] = clearColor.normA();

                    if (samplerState) samplerState->Release();

                    RendererD3D11::SamplerStateDesc samplerDesc;
                    samplerDesc.filter = (filter == Texture::Filter::DEFAULT) ? rendererD3D11->getTextureFilter() : filter;
                    samplerDesc.addressX = addressX;
                    samplerDesc.addressY = addressY;
                    samplerDesc.maxAnisotropy = (maxAnisotropy == 0) ? rendererD3D11->getMaxAnisotropy() : maxAnisotropy;

                    samplerState = rendererD3D11->getSamplerState(samplerDesc);

                    if (!samplerState)
                    {
                        Log(Log::Level::ERR) << "Failed to get D3D11 sampler state";
                        return false;
                    }

                    samplerState->AddRef();
                }

                dirty = 0;
            }

            return true;
        }
    } // namespace graphics
} // namespace ouzel
<commit_msg>If the pitches are equal copy the whole buffer<commit_after>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "TextureResourceD3D11.h"
#include "RendererD3D11.h"
#include "core/Engine.h"
#include "utils/Log.h"

namespace ouzel
{
    namespace graphics
    {
        static DXGI_FORMAT getD3D11PixelFormat(PixelFormat pixelFormat)
        {
            switch (pixelFormat)
            {
                case PixelFormat::A8_UNORM: return DXGI_FORMAT_A8_UNORM;
                case PixelFormat::R8_UNORM: return DXGI_FORMAT_R8_UNORM;
                case PixelFormat::R8_SNORM: return DXGI_FORMAT_R8_SNORM;
                case PixelFormat::R8_UINT: return DXGI_FORMAT_R8_UINT;
                case PixelFormat::R8_SINT: return DXGI_FORMAT_R8_SINT;
                case PixelFormat::R16_UNORM: return DXGI_FORMAT_R16_UNORM;
                case PixelFormat::R16_SNORM: return DXGI_FORMAT_R16_SNORM;
                case PixelFormat::R16_UINT: return DXGI_FORMAT_R16_UINT;
                case PixelFormat::R16_SINT: return DXGI_FORMAT_R16_SINT;
                case PixelFormat::R16_FLOAT: return DXGI_FORMAT_R16_FLOAT;
                case PixelFormat::R32_UINT: return DXGI_FORMAT_R32_UINT;
                case PixelFormat::R32_SINT: return DXGI_FORMAT_R32_SINT;
                case PixelFormat::R32_FLOAT: return DXGI_FORMAT_R32_FLOAT;
                case PixelFormat::RG8_UNORM: return DXGI_FORMAT_R8G8_UNORM;
                case PixelFormat::RG8_SNORM: return DXGI_FORMAT_R8G8_SNORM;
                case PixelFormat::RG8_UINT: return DXGI_FORMAT_R8G8_UINT;
                case PixelFormat::RG8_SINT: return DXGI_FORMAT_R8G8_SINT;
                case PixelFormat::RGBA8_UNORM: return DXGI_FORMAT_R8G8B8A8_UNORM;
                case PixelFormat::RGBA8_SNORM: return DXGI_FORMAT_R8G8B8A8_SNORM;
                case PixelFormat::RGBA8_UINT: return DXGI_FORMAT_R8G8B8A8_UINT;
                case PixelFormat::RGBA8_SINT: return DXGI_FORMAT_R8G8B8A8_SINT;
                case PixelFormat::RGBA16_UNORM: return DXGI_FORMAT_R16G16B16A16_UNORM;
                case PixelFormat::RGBA16_SNORM: return DXGI_FORMAT_R16G16B16A16_SNORM;
                case PixelFormat::RGBA16_UINT: return DXGI_FORMAT_R16G16B16A16_UINT;
                case PixelFormat::RGBA16_SINT: return DXGI_FORMAT_R16G16B16A16_SINT;
                case PixelFormat::RGBA16_FLOAT: return DXGI_FORMAT_R16G16B16A16_FLOAT;
                case PixelFormat::RGBA32_UINT: return DXGI_FORMAT_R32G32B32A32_UINT;
                case PixelFormat::RGBA32_SINT: return DXGI_FORMAT_R32G32B32A32_SINT;
                case PixelFormat::RGBA32_FLOAT: return DXGI_FORMAT_R32G32B32A32_FLOAT;
                default: return DXGI_FORMAT_UNKNOWN;
            }
        }

        TextureResourceD3D11::TextureResourceD3D11()
        {
        }

        TextureResourceD3D11::~TextureResourceD3D11()
        {
            if (depthStencilTexture)
            {
                depthStencilTexture->Release();
            }

            if (depthStencilView)
            {
                depthStencilView->Release();
            }

            if (renderTargetView)
            {
                renderTargetView->Release();
            }

            if (resourceView)
            {
                resourceView->Release();
            }

            if (texture)
            {
                texture->Release();
            }

            if (samplerState)
            {
                samplerState->Release();
            }

            width = 0;
            height = 0;
        }

        bool TextureResourceD3D11::upload()
        {
            std::lock_guard<std::mutex> lock(uploadMutex);

            if (dirty)
            {
                RendererD3D11* rendererD3D11 = static_cast<RendererD3D11*>(sharedEngine->getRenderer());

                if (dirty & DIRTY_DATA)
                {
                    if (size.v[0] > 0 &&
                        size.v[1] > 0)
                    {
                        if (!texture ||
                            static_cast<UINT>(size.v[0]) != width ||
                            static_cast<UINT>(size.v[1]) != height)
                        {
                            if (texture)
                            {
                                texture->Release();
                            }

                            if (resourceView)
                            {
                                resourceView->Release();
                                resourceView = nullptr;
                            }

                            width = static_cast<UINT>(size.v[0]);
                            height = static_cast<UINT>(size.v[1]);

                            DXGI_FORMAT d3d11PixelFormat = getD3D11PixelFormat(pixelFormat);

                            if (d3d11PixelFormat == DXGI_FORMAT_UNKNOWN)
                            {
                                Log(Log::Level::ERR) << "Invalid pixel format";
                                return false;
                            }

                            D3D11_TEXTURE2D_DESC textureDesc;
                            textureDesc.Width = width;
                            textureDesc.Height = height;
                            textureDesc.MipLevels = (levels.size() > 1) ? 0 : 1;
                            textureDesc.ArraySize = 1;
                            textureDesc.Format = d3d11PixelFormat;
                            textureDesc.Usage = (dynamic && !renderTarget) ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT;
                            textureDesc.CPUAccessFlags = (dynamic && !renderTarget) ? D3D11_CPU_ACCESS_WRITE : 0;
                            textureDesc.SampleDesc.Count = sampleCount;
                            textureDesc.SampleDesc.Quality = 0;
                            textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | (renderTarget ? D3D11_BIND_RENDER_TARGET : 0);
                            textureDesc.MiscFlags = 0;

                            HRESULT hr = rendererD3D11->getDevice()->CreateTexture2D(&textureDesc, nullptr, &texture);
                            if (FAILED(hr))
                            {
                                Log(Log::Level::ERR) << "Failed to create Direct3D 11 texture, error: " << hr;
                                return false;
                            }

                            D3D11_SHADER_RESOURCE_VIEW_DESC resourceViewDesc;
                            resourceViewDesc.Format = d3d11PixelFormat;
                            resourceViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_SRV_DIMENSION_TEXTURE2DMS : D3D11_SRV_DIMENSION_TEXTURE2D;

                            if (sampleCount == 1)
                            {
                                resourceViewDesc.Texture2D.MostDetailedMip = 0;
                                resourceViewDesc.Texture2D.MipLevels = static_cast<UINT>(levels.size());
                            }

                            hr = rendererD3D11->getDevice()->CreateShaderResourceView(texture, &resourceViewDesc, &resourceView);
                            if (FAILED(hr))
                            {
                                Log(Log::Level::ERR) << "Failed to create Direct3D 11 shader resource view, error: " << hr;
                                return false;
                            }

                            if (renderTarget)
                            {
                                if (renderTargetView)
                                {
                                    renderTargetView->Release();
                                }

                                D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
                                renderTargetViewDesc.Format = d3d11PixelFormat;
                                renderTargetViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D;

                                if (sampleCount == 1)
                                {
                                    renderTargetViewDesc.Texture2D.MipSlice = 0;
                                }

                                hr = rendererD3D11->getDevice()->CreateRenderTargetView(texture, &renderTargetViewDesc, &renderTargetView);
                                if (FAILED(hr))
                                {
                                    Log(Log::Level::ERR) << "Failed to create Direct3D 11 render target view, error: " << hr;
                                    return false;
                                }
                            }

                            if (depth)
                            {
                                if (depthStencilTexture)
                                {
                                    depthStencilTexture->Release();
                                }

                                if (depthStencilView)
                                {
                                    depthStencilView->Release();
                                    depthStencilView = nullptr;
                                }

                                D3D11_TEXTURE2D_DESC depthStencilDesc;
                                depthStencilDesc.Width = width;
                                depthStencilDesc.Height = height;
                                depthStencilDesc.MipLevels = 1;
                                depthStencilDesc.ArraySize = 1;
                                depthStencilDesc.Format = DXGI_FORMAT_D32_FLOAT;
                                depthStencilDesc.SampleDesc.Count = sampleCount;
                                depthStencilDesc.SampleDesc.Quality = 0;
                                depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
                                depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
                                depthStencilDesc.CPUAccessFlags = 0;
                                depthStencilDesc.MiscFlags = 0;
                                hr = rendererD3D11->getDevice()->CreateTexture2D(&depthStencilDesc, nullptr, &depthStencilTexture);
                                if (FAILED(hr))
                                {
                                    Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil texture, error: " << hr;
                                    return false;
                                }

                                hr = rendererD3D11->getDevice()->CreateDepthStencilView(depthStencilTexture, nullptr, &depthStencilView);
                                if (FAILED(hr))
                                {
                                    Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil view, error: " << hr;
                                    return false;
                                }
                            }
                        }

                        if (dynamic)
                        {
                            for (size_t level = 0; level < levels.size(); ++level)
                            {
                                if (!levels[level].data.empty())
                                {
                                    D3D11_MAPPED_SUBRESOURCE mappedSubresource;
                                    mappedSubresource.pData = 0;
                                    mappedSubresource.RowPitch = 0;
                                    mappedSubresource.DepthPitch = 0;

                                    HRESULT hr = rendererD3D11->getContext()->Map(texture, static_cast<UINT>(level),
                                                                                (level == 0) ? D3D11_MAP_WRITE_DISCARD : D3D11_MAP_WRITE,
                                                                                0, &mappedSubresource);

                                    if (FAILED(hr))
                                    {
                                        Log(Log::Level::ERR) << "Failed to map Direct3D 11 texture, error: " << hr;
                                        return false;
                                    }

                                    uint8_t* target = reinterpret_cast<uint8_t*>(mappedSubresource.pData);

                                    if (mappedSubresource.RowPitch == levels[level].pitch)
                                    {
                                        std::copy(levels[level].data.begin(),
                                                  levels[level].data.end(),
                                                  target);
                                    }
                                    else
                                    {
                                        for (UINT row = 0; row < height; ++row)
                                        {
                                            std::copy(levels[level].data.begin() + row * levels[level].pitch,
                                                      levels[level].data.begin() + (row + 1) * levels[level].pitch,
                                                      target);

                                            target += mappedSubresource.RowPitch;
                                        }

                                        rendererD3D11->getContext()->Unmap(texture, static_cast<UINT>(level));
                                    }
                                }
                            }
                        }
                        else
                        {
                            for (size_t level = 0; level < levels.size(); ++level)
                            {
                                if (!levels[level].data.empty())
                                {
                                    rendererD3D11->getContext()->UpdateSubresource(texture, static_cast<UINT>(level),
                                                                                nullptr, levels[level].data.data(),
                                                                                static_cast<UINT>(levels[level].pitch), 0);
                                }
                            }
                        }
                    }
                }

                if (dirty & DIRTY_PARAMETERS)
                {
                    clearFrameBufferView = clearColorBuffer;
                    clearDepthBufferView = clearDepthBuffer;

                    frameBufferClearColor[0] = clearColor.normR();
                    frameBufferClearColor[1] = clearColor.normG();
                    frameBufferClearColor[2] = clearColor.normB();
                    frameBufferClearColor[3] = clearColor.normA();

                    if (samplerState) samplerState->Release();

                    RendererD3D11::SamplerStateDesc samplerDesc;
                    samplerDesc.filter = (filter == Texture::Filter::DEFAULT) ? rendererD3D11->getTextureFilter() : filter;
                    samplerDesc.addressX = addressX;
                    samplerDesc.addressY = addressY;
                    samplerDesc.maxAnisotropy = (maxAnisotropy == 0) ? rendererD3D11->getMaxAnisotropy() : maxAnisotropy;

                    samplerState = rendererD3D11->getSamplerState(samplerDesc);

                    if (!samplerState)
                    {
                        Log(Log::Level::ERR) << "Failed to get D3D11 sampler state";
                        return false;
                    }

                    samplerState->AddRef();
                }

                dirty = 0;
            }

            return true;
        }
    } // namespace graphics
} // namespace ouzel
<|endoftext|>


<commit_before>#include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Input.h"
#include "j1Textures.h"
#include "j1Audio.h"
#include "j1Render.h"
#include "j1Window.h"
#include "j1Map.h"
#include "j1Colliders.h"
#include "j1Scene.h"
#include "j1Scene2.h"
#include "j1Player.h"

j1Scene::j1Scene() : j1Module()
{
	name.create("scene");
}

// Destructor
j1Scene::~j1Scene()
{}

// Called before render is available
bool j1Scene::Awake(pugi::xml_node& config)
{
	LOG("Loading Scene");
	bool ret = true;

	return ret;
}

// Called before the first frame
bool j1Scene::Start()
{

	App->map->Load("test.tmx");

	App->audio->PlayMusic("audio/music/map1_music.ogg");
	//Colliders
	//App->colliders->AddCollider({ 0,415,10000,10 }, COLLIDER_FLOOR);
	App->map->Draw_Colliders();

	return true;
}

// Called each loop iteration
bool j1Scene::PreUpdate()
{
	return true;
}

// Called each loop iteration
bool j1Scene::Update(float dt)
{
	if(App->input->GetKey(SDL_SCANCODE_F5) == KEY_DOWN)
		App->SaveGame();

	if(App->input->GetKey(SDL_SCANCODE_F6) == KEY_DOWN)
		App->LoadGame();

	if (App->input->GetKey(SDL_SCANCODE_F2) == KEY_DOWN)
	{
		active = false;
		App->scene2->active = true;
		CleanUp();
		App->scene2->Start();
		App->player->position.y = 215;
	}

	if (App->player->position.x >= App->player->win_width/2 && App->player->position.x <= 15000)//App->player->win_width)
	{
		App->render->camera.x =- App->player->position.x + App->player->win_width / 2;
	}

	//App->render->Blit(img, 0, 0);
	App->map->Draw();

	// TODO 7: Set the window title like
	// "Map:%dx%d Tiles:%dx%d Tilesets:%d"
	p2SString title("Map:%dx%d Tiles:%dx%d Tilesets:%d Player.x=%i Player.y=%i CameraPosition.x=%i CameraPosition.y=%i Acceleration=%d X=%d Y=%d",
					App->map->data.width, App->map->data.height,
					App->map->data.tile_width, App->map->data.tile_height,
					App->map->data.tilesets.count(), App->player->position.x,
					App->player->position.y, App->render->camera.x,
					App->render->camera.y, App->player->acceleration,
					App->player->position.x,App->player->position.y);

	App->win->SetTitle(title.GetString());
	return true;
}

// Called each loop iteration
bool j1Scene::PostUpdate()
{
	bool ret = true;

	if(App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN)
		ret = false;

	return ret;
}

// Called before quitting
bool j1Scene::CleanUp()
{
	LOG("Freeing scene");
	App->map->CleanUp();
	App->colliders->CleanUp();

	return true;
}
<commit_msg>player x reload<commit_after>#include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Input.h"
#include "j1Textures.h"
#include "j1Audio.h"
#include "j1Render.h"
#include "j1Window.h"
#include "j1Map.h"
#include "j1Colliders.h"
#include "j1Scene.h"
#include "j1Scene2.h"
#include "j1Player.h"

j1Scene::j1Scene() : j1Module()
{
	name.create("scene");
}

// Destructor
j1Scene::~j1Scene()
{}

// Called before render is available
bool j1Scene::Awake(pugi::xml_node& config)
{
	LOG("Loading Scene");
	bool ret = true;

	return ret;
}

// Called before the first frame
bool j1Scene::Start()
{

	App->map->Load("untitled.tmx");

	App->audio->PlayMusic("audio/music/map1_music.ogg");
	//Colliders
	//App->colliders->AddCollider({ 0,415,10000,10 }, COLLIDER_FLOOR);
	App->map->Draw_Colliders();

	return true;
}

// Called each loop iteration
bool j1Scene::PreUpdate()
{
	return true;
}

// Called each loop iteration
bool j1Scene::Update(float dt)
{
	if(App->input->GetKey(SDL_SCANCODE_F5) == KEY_DOWN)
		App->SaveGame();

	if(App->input->GetKey(SDL_SCANCODE_F6) == KEY_DOWN)
		App->LoadGame();

	if (App->input->GetKey(SDL_SCANCODE_F2) == KEY_DOWN)
	{
		active = false;
		App->scene2->active = true;
		CleanUp();
		App->scene2->Start();
		App->player->position.y = 215;
		App->player->position.x = 60;
	}

	if (App->player->position.x >= App->player->win_width/2 && App->player->position.x <= 15000)//App->player->win_width)
	{
		App->render->camera.x =- App->player->position.x + App->player->win_width / 2;
	}

	//App->render->Blit(img, 0, 0);
	App->map->Draw();

	// TODO 7: Set the window title like
	// "Map:%dx%d Tiles:%dx%d Tilesets:%d"
	p2SString title("Map:%dx%d Tiles:%dx%d Tilesets:%d Player.x=%i Player.y=%i CameraPosition.x=%i CameraPosition.y=%i Acceleration=%d X=%d Y=%d",
					App->map->data.width, App->map->data.height,
					App->map->data.tile_width, App->map->data.tile_height,
					App->map->data.tilesets.count(), App->player->position.x,
					App->player->position.y, App->render->camera.x,
					App->render->camera.y, App->player->acceleration,
					App->player->position.x,App->player->position.y);

	App->win->SetTitle(title.GetString());
	return true;
}

// Called each loop iteration
bool j1Scene::PostUpdate()
{
	bool ret = true;

	if(App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN)
		ret = false;

	return ret;
}

// Called before quitting
bool j1Scene::CleanUp()
{
	LOG("Freeing scene");
	App->map->CleanUp();
	App->colliders->CleanUp();

	return true;
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 - Decho Corp.

#include "mordor/common/pch.h"

#include "oauth.h"

#include "mordor/common/streams/memory.h"
#include "mordor/common/streams/transfer.h"

void
HTTP::OAuth::authorize(Request &nextRequest)
{
    if (m_params.find("oauth_token_secret") == m_params.end() ||
        m_params.find("oauth_token") == m_params.end()) {
        getRequestToken();
        getAccessToken(m_authDg(m_params));
    }
    AuthParams &authorization = nextRequest.request.authorization;
    authorization.scheme = "OAuth";
    URI::QueryString params = signRequest(nextRequest.requestLine.uri,
        nextRequest.requestLine.method);
    authorization.parameters.clear();
    authorization.parameters.insert(params.begin(), params.end());
}

void
HTTP::OAuth::getRequestToken()
{
    ASSERT(m_requestTokenMethod == HTTP::GET || m_requestTokenMethod == HTTP::POST);
    URI::QueryString qs;

    qs.insert(std::make_pair("oauth_consumer_key", m_consumerKey));
    qs.insert(std::make_pair("oauth_version", "1.0"));
    qs.insert(std::make_pair("oauth_callback", "oob"));
    nonceAndTimestamp(qs);
    sign(m_requestTokenUri, m_requestTokenMethod, qs);

    HTTP::Request requestHeaders;
    requestHeaders.requestLine.method = m_requestTokenMethod;
    requestHeaders.requestLine.uri = m_requestTokenUri;
    std::string body;
    if (m_requestTokenMethod == HTTP::GET) {
        // Add parameters that are part of the request token URI
        URI::QueryString qsFromUri = m_requestTokenUri.queryString();
        qs.insert(qsFromUri.begin(), qsFromUri.end());
        requestHeaders.requestLine.uri.query(qs);
    } else {
        body = qs.toString();
        requestHeaders.entity.contentType.type = "application";
        requestHeaders.entity.contentType.subtype = "x-www-form-urlencoded";
        requestHeaders.entity.contentLength = body.size();
    }

    HTTP::ClientRequest::ptr request =
        m_connDg(m_requestTokenUri)->request(requestHeaders);
    if (!body.empty()) {
        request->requestStream()->write(body.c_str(), body.size());
        request->requestStream()->close();
    }
    if (request->response().status.status != HTTP::OK) {
        request->cancel();
        throw HTTP::InvalidResponseException("", request->response());
    }

    MemoryStream responseStream;
    transferStream(request->responseStream(), responseStream);
    std::string response;
    response.resize(responseStream.buffer().readAvailable());
    responseStream.buffer().copyOut(&response[0], responseStream.buffer().readAvailable());
    m_params = response;
    URI::QueryString::iterator it = m_params.find("oauth_token");
    if (it == m_params.end())
        throw HTTP::InvalidResponseException("Missing oauth_token in response",
            request->response());
    ++it;
    if (it != m_params.end() &&
        stricmp(it->first.c_str(), "oauth_token") == 0)
        throw HTTP::InvalidResponseException("Duplicate oauth_token in response",
            request->response());
    it = m_params.find("oauth_token_secret");
    if (it == m_params.end())
        throw HTTP::InvalidResponseException("Missing oauth_token_secret in response",
            request->response());
    ++it;
    if (it != m_params.end() &&
        stricmp(it->first.c_str(), "oauth_token_secret") == 0)
        throw HTTP::InvalidResponseException("Duplicate oauth_token_secret in response",
            request->response());
}

void
HTTP::OAuth::getAccessToken(const std::string &verifier)
{
    ASSERT(m_accessTokenMethod == HTTP::GET || m_accessTokenMethod == HTTP::POST);
    URI::QueryString qs;

    qs.insert(std::make_pair("oauth_consumer_key", m_consumerKey));
    qs.insert(*m_params.find("oauth_token"));
    qs.insert(std::make_pair("oauth_verifier", verifier));
    qs.insert(std::make_pair("oauth_version", "1.0"));
    nonceAndTimestamp(qs);
    sign(m_accessTokenUri, m_accessTokenMethod, qs);

    HTTP::Request requestHeaders;
    requestHeaders.requestLine.method = m_accessTokenMethod;
    requestHeaders.requestLine.uri = m_accessTokenUri;
    std::string body;
    if (m_accessTokenMethod == HTTP::GET) {
        // Add parameters that are part of the request token URI
        URI::QueryString qsFromUri = m_accessTokenUri.queryString();
        qs.insert(qsFromUri.begin(), qsFromUri.end());
        requestHeaders.requestLine.uri.query(qs);
    } else {
        body = qs.toString();
        requestHeaders.entity.contentType.type = "application";
        requestHeaders.entity.contentType.subtype = "x-www-form-urlencoded";
        requestHeaders.entity.contentLength = body.size();
    }

    HTTP::ClientRequest::ptr request =
        m_connDg(m_accessTokenUri)->request(requestHeaders);
    if (!body.empty()) {
        request->requestStream()->write(body.c_str(), body.size());
        request->requestStream()->close();
    }
    if (request->response().status.status != HTTP::OK) {
        request->cancel();
        throw HTTP::InvalidResponseException("", request->response());
    }

    MemoryStream responseStream;
    transferStream(request->responseStream(), responseStream);
    std::string response;
    response.resize(responseStream.buffer().readAvailable());
    responseStream.buffer().copyOut(&response[0], responseStream.buffer().readAvailable());
    m_params = response;
    URI::QueryString::iterator it = m_params.find("oauth_token");
    if (it == m_params.end())
        throw HTTP::InvalidResponseException("Missing oauth_token in response",
            request->response());
    ++it;
    if (it != m_params.end() &&
        stricmp(it->first.c_str(), "oauth_token") == 0)
        throw HTTP::InvalidResponseException("Duplicate oauth_token in response",
            request->response());
    it = m_params.find("oauth_token_secret");
    if (it == m_params.end())
        throw HTTP::InvalidResponseException("Missing oauth_token_secret in response",
            request->response());
    ++it;
    if (it != m_params.end() &&
        stricmp(it->first.c_str(), "oauth_token_secret") == 0)
        throw HTTP::InvalidResponseException("Duplicate oauth_token_secret in response",
            request->response());
}

URI::QueryString
HTTP::OAuth::signRequest(const URI &uri, Method method)
{
    URI::QueryString result;
    result.insert(std::make_pair("oauth_consumer_key", m_consumerKey));
    result.insert(*m_params.find("oauth_token"));
    result.insert(std::make_pair("oauth_version", "1.0"));
    nonceAndTimestamp(result);
    sign(uri, method, result);
    return result;
}

void
HTTP::OAuth::nonceAndTimestamp(URI::QueryString &params)
{
    // TODO: fill in with better data
    params.insert(std::make_pair("oauth_timestamp", "123"));
    params.insert(std::make_pair("oauth_nonce", "abc"));
}

void
HTTP::OAuth::sign(URI uri, Method method, URI::QueryString &params)
{
    std::string signatureMethod;
    URI::QueryString::iterator it = params.find("oauth_signature_method");
    if (it == params.end()) {
        params.insert(std::make_pair("oauth_signature_method", "PLAINTEXT"));
        signatureMethod = "PLAINTEXT";
    } else {
        signatureMethod = it->second;
    }
    it = params.find("oauth_signature");
    if (it != params.end())
        params.erase(it);

    std::ostringstream os;
    uri.queryDefined(false);
    uri.fragmentDefined(false);
    uri.normalize();
    os << method << '&' << uri;
    URI::QueryString combined = params;
    it = combined.find("realm");
    if (it != combined.end())
        combined.erase(it);
    // TODO: POST params of application/x-www-form-urlencoded
    if (uri.queryDefined()) {
        URI::QueryString queryParams = uri.queryString();
        combined.insert(queryParams.begin(), queryParams.end());
    }

    // TODO: ordering of duplicate keys
    std::string signatureBaseString = combined.toString();

    std::string secrets = URI::encode(m_consumerSecret, URI::QUERYSTRING);
    secrets.append(1, '&');
    secrets.append(URI::encode(m_params.find("oauth_token_secret")->second,
        URI::QUERYSTRING));

    if (stricmp(signatureMethod.c_str(), "HMAC-SHA1") == 0) {
        params.insert(std::make_pair("oauth_signature",
            hmacSha1(signatureBaseString, secrets)));
    } else if (stricmp(signatureMethod.c_str(), "PLAINTEXT") == 0) {
        params.insert(std::make_pair("oauth_signature", secrets));
    } else {
        NOTREACHED();
    }
}
<commit_msg>Use actual nonce and timestamps.  Follow the spec for formation of the signature base string.<commit_after>// Copyright (c) 2009 - Decho Corp.

#include "mordor/common/pch.h"

#include "oauth.h"

#include "mordor/common/streams/memory.h"
#include "mordor/common/streams/transfer.h"

void
HTTP::OAuth::authorize(Request &nextRequest)
{
    if (m_params.find("oauth_token_secret") == m_params.end() ||
        m_params.find("oauth_token") == m_params.end()) {
        getRequestToken();
        getAccessToken(m_authDg(m_params));
    }
    AuthParams &authorization = nextRequest.request.authorization;
    authorization.scheme = "OAuth";
    URI::QueryString params = signRequest(nextRequest.requestLine.uri,
        nextRequest.requestLine.method);
    authorization.parameters.clear();
    authorization.parameters.insert(params.begin(), params.end());
}

void
HTTP::OAuth::getRequestToken()
{
    ASSERT(m_requestTokenMethod == HTTP::GET || m_requestTokenMethod == HTTP::POST);
    URI::QueryString qs;

    qs.insert(std::make_pair("oauth_consumer_key", m_consumerKey));
    qs.insert(std::make_pair("oauth_version", "1.0"));
    qs.insert(std::make_pair("oauth_callback", "oob"));
    nonceAndTimestamp(qs);
    sign(m_requestTokenUri, m_requestTokenMethod, qs);

    HTTP::Request requestHeaders;
    requestHeaders.requestLine.method = m_requestTokenMethod;
    requestHeaders.requestLine.uri = m_requestTokenUri;
    std::string body;
    if (m_requestTokenMethod == HTTP::GET) {
        // Add parameters that are part of the request token URI
        URI::QueryString qsFromUri = m_requestTokenUri.queryString();
        qs.insert(qsFromUri.begin(), qsFromUri.end());
        requestHeaders.requestLine.uri.query(qs);
    } else {
        body = qs.toString();
        requestHeaders.entity.contentType.type = "application";
        requestHeaders.entity.contentType.subtype = "x-www-form-urlencoded";
        requestHeaders.entity.contentLength = body.size();
    }

    HTTP::ClientRequest::ptr request =
        m_connDg(m_requestTokenUri)->request(requestHeaders);
    if (!body.empty()) {
        request->requestStream()->write(body.c_str(), body.size());
        request->requestStream()->close();
    }
    if (request->response().status.status != HTTP::OK) {
        request->cancel();
        throw HTTP::InvalidResponseException("", request->response());
    }

    MemoryStream responseStream;
    transferStream(request->responseStream(), responseStream);
    std::string response;
    response.resize(responseStream.buffer().readAvailable());
    responseStream.buffer().copyOut(&response[0], responseStream.buffer().readAvailable());
    m_params = response;
    URI::QueryString::iterator it = m_params.find("oauth_token");
    if (it == m_params.end())
        throw HTTP::InvalidResponseException("Missing oauth_token in response",
            request->response());
    ++it;
    if (it != m_params.end() &&
        stricmp(it->first.c_str(), "oauth_token") == 0)
        throw HTTP::InvalidResponseException("Duplicate oauth_token in response",
            request->response());
    it = m_params.find("oauth_token_secret");
    if (it == m_params.end())
        throw HTTP::InvalidResponseException("Missing oauth_token_secret in response",
            request->response());
    ++it;
    if (it != m_params.end() &&
        stricmp(it->first.c_str(), "oauth_token_secret") == 0)
        throw HTTP::InvalidResponseException("Duplicate oauth_token_secret in response",
            request->response());
}

void
HTTP::OAuth::getAccessToken(const std::string &verifier)
{
    ASSERT(m_accessTokenMethod == HTTP::GET || m_accessTokenMethod == HTTP::POST);
    URI::QueryString qs;

    qs.insert(std::make_pair("oauth_consumer_key", m_consumerKey));
    qs.insert(*m_params.find("oauth_token"));
    qs.insert(std::make_pair("oauth_verifier", verifier));
    qs.insert(std::make_pair("oauth_version", "1.0"));
    nonceAndTimestamp(qs);
    sign(m_accessTokenUri, m_accessTokenMethod, qs);

    HTTP::Request requestHeaders;
    requestHeaders.requestLine.method = m_accessTokenMethod;
    requestHeaders.requestLine.uri = m_accessTokenUri;
    std::string body;
    if (m_accessTokenMethod == HTTP::GET) {
        // Add parameters that are part of the request token URI
        URI::QueryString qsFromUri = m_accessTokenUri.queryString();
        qs.insert(qsFromUri.begin(), qsFromUri.end());
        requestHeaders.requestLine.uri.query(qs);
    } else {
        body = qs.toString();
        requestHeaders.entity.contentType.type = "application";
        requestHeaders.entity.contentType.subtype = "x-www-form-urlencoded";
        requestHeaders.entity.contentLength = body.size();
    }

    HTTP::ClientRequest::ptr request =
        m_connDg(m_accessTokenUri)->request(requestHeaders);
    if (!body.empty()) {
        request->requestStream()->write(body.c_str(), body.size());
        request->requestStream()->close();
    }
    if (request->response().status.status != HTTP::OK) {
        request->cancel();
        throw HTTP::InvalidResponseException("", request->response());
    }

    MemoryStream responseStream;
    transferStream(request->responseStream(), responseStream);
    std::string response;
    response.resize(responseStream.buffer().readAvailable());
    responseStream.buffer().copyOut(&response[0], responseStream.buffer().readAvailable());
    m_params = response;
    URI::QueryString::iterator it = m_params.find("oauth_token");
    if (it == m_params.end())
        throw HTTP::InvalidResponseException("Missing oauth_token in response",
            request->response());
    ++it;
    if (it != m_params.end() &&
        stricmp(it->first.c_str(), "oauth_token") == 0)
        throw HTTP::InvalidResponseException("Duplicate oauth_token in response",
            request->response());
    it = m_params.find("oauth_token_secret");
    if (it == m_params.end())
        throw HTTP::InvalidResponseException("Missing oauth_token_secret in response",
            request->response());
    ++it;
    if (it != m_params.end() &&
        stricmp(it->first.c_str(), "oauth_token_secret") == 0)
        throw HTTP::InvalidResponseException("Duplicate oauth_token_secret in response",
            request->response());
}

URI::QueryString
HTTP::OAuth::signRequest(const URI &uri, Method method)
{
    URI::QueryString result;
    result.insert(std::make_pair("oauth_consumer_key", m_consumerKey));
    result.insert(*m_params.find("oauth_token"));
    result.insert(std::make_pair("oauth_version", "1.0"));
    nonceAndTimestamp(result);
    sign(uri, method, result);
    return result;
}

void
HTTP::OAuth::nonceAndTimestamp(URI::QueryString &params)
{
    static boost::posix_time::ptime start(boost::gregorian::date(1970, 1, 1));
    static const char *allowedChars =
        "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    std::ostringstream os;
    boost::posix_time::ptime now =
        boost::posix_time::second_clock::universal_time();
    boost::posix_time::time_duration duration = now - start;
    os << duration.total_seconds();

    std::string nonce;
    nonce.resize(40);
    for (size_t i = 0; i < 40; ++i) {
        nonce[i] = allowedChars[rand() % 36];
    }

    params.insert(std::make_pair("oauth_timestamp", os.str()));
    params.insert(std::make_pair("oauth_nonce", nonce));
}

void
HTTP::OAuth::sign(URI uri, Method method, URI::QueryString &params)
{
    std::string signatureMethod;
    URI::QueryString::iterator it = params.find("oauth_signature_method");
    if (it == params.end()) {
        params.insert(std::make_pair("oauth_signature_method", "PLAINTEXT"));
        signatureMethod = "PLAINTEXT";
    } else {
        signatureMethod = it->second;
    }
    it = params.find("oauth_signature");
    if (it != params.end())
        params.erase(it);

    std::ostringstream os;
    uri.queryDefined(false);
    uri.fragmentDefined(false);
    uri.normalize();
    os << method << '&' << uri;
    std::map<std::string, std::multiset<std::string> > combined;
    std::map<std::string, std::multiset<std::string> >::iterator
        combinedIt;
    for (it = params.begin(); it != params.end(); ++it)
        if (stricmp(it->first.c_str(), "realm") != 0)
            combined[it->first].insert(it->second);
    // TODO: POST params of application/x-www-form-urlencoded
    if (uri.queryDefined()) {
        URI::QueryString queryParams = uri.queryString();
        for (it = queryParams.begin(); it != queryParams.end(); ++it)
            combined[it->first].insert(it->second);
    }

    for (combinedIt = combined.begin();
        combinedIt != combined.end();
        ++combinedIt) {
        for (std::multiset<std::string>::iterator it2 =
            combinedIt->second.begin();
            it2 != combinedIt->second.end();
            ++it2) {
            os << '&' << URI::encode(combinedIt->first, URI::QUERYSTRING)
                << '=' << URI::encode(*it2, URI::QUERYSTRING);
        }
    }
    std::string signatureBaseString = os.str();

    std::string secrets = URI::encode(m_consumerSecret, URI::QUERYSTRING);
    secrets.append(1, '&');
    secrets.append(URI::encode(m_params.find("oauth_token_secret")->second,
        URI::QUERYSTRING));

    if (stricmp(signatureMethod.c_str(), "HMAC-SHA1") == 0) {
        params.insert(std::make_pair("oauth_signature",
            hmacSha1(signatureBaseString, secrets)));
    } else if (stricmp(signatureMethod.c_str(), "PLAINTEXT") == 0) {
        params.insert(std::make_pair("oauth_signature", secrets));
    } else {
        NOTREACHED();
    }
}
<|endoftext|>


<commit_before>//////////////////////////////// -*- C++ -*- /////////////////////////////
//
// FILE NAME
//   ParticleAttributesFactory.cc
//
// AUTHOR
//    A. Shishlo
//
// CREATED
//    07/16/2005
//
// DESCRIPTION
//    A factory class for particle attributes classes.
//    Usually it will be used from a Bunch class instance.
//
///////////////////////////////////////////////////////////////////////////

#include "ParticleAttributesFactory.hh"

#include "ParticleMacroSize.hh"
#include "WaveFunctionAmplitudes.hh"
#include "AtomPopulations.hh"
#include "pq_coordinates.hh"
#include "part_time.hh"
#include "Evolution.hh"
#include "LostParticleAttributes.hh"

ParticleAttributesFactory::ParticleAttributesFactory()
{
}

ParticleAttributesFactory::~ParticleAttributesFactory()
{
}

ParticleAttributes* ParticleAttributesFactory::getParticleAttributesInstance(
	const string name,
	std::map<std::string,double> params_dict,
	Bunch* bunch)
{
	//for MPI --- start
	int rank_MPI = 0;
	int size_MPI = 1;
	int iMPIini  = 0;
	MPI_Comm MPI_COMM_Local = bunch->getMPI_Comm_Local()->comm;
	ORBIT_MPI_Initialized(&iMPIini);

	if(iMPIini > 0){
		ORBIT_MPI_Comm_size(MPI_COMM_Local, &size_MPI);
		ORBIT_MPI_Comm_rank(MPI_COMM_Local, &rank_MPI);
	}
	//for MPI --- stop

  ParticleAttributes* part_atrs = NULL;
  if(name == "empty"){
    part_atrs = new ParticleAttributes(bunch,0);
  }

  if(name == "macrosize"){
    part_atrs = new ParticleMacroSize(bunch);
  }

  if(name == "LostParticleAttributes"){
	part_atrs = new LostParticleAttributes(bunch);
  }

  if(name == "Amplitudes"){
		if(params_dict.size() == 0){
			cout<<"dictionary Amplitudes(dict) should be defined "<<"\n";
		} else {
			if(params_dict.count("size") == 1){
				part_atrs = new WaveFunctionAmplitudes(bunch,(int) params_dict["size"]);
			} else {
				if(rank_MPI == 0){
					std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(name,dict)"<< std::endl;
					std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl;
					std::cerr << "MPI size="<< size_MPI << std::endl;
					std::cerr << "MPI rank="<< rank_MPI << std::endl;
					std::cerr << "attr. name:"<< name << std::endl;
					std::cerr << "There is no <size> specification in the dict. "<< std::endl;
				}
				ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop.");
			}
		}
  }

  if(name == "Populations"){
		if(params_dict.size() == 0){
			cout<<"dictionary AtomPopulations(dict) should be defined "<<"\n";
		} else {
			if(params_dict.count("size") == 1){
				part_atrs = new AtomPopulations(bunch,(int) params_dict["size"]);
			} else {
				if(rank_MPI == 0){
					std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(name,dict)"<< std::endl;
					std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl;
					std::cerr << "MPI size="<< size_MPI << std::endl;
					std::cerr << "MPI rank="<< rank_MPI << std::endl;
					std::cerr << "attr. name:"<< name << std::endl;
					std::cerr << "There is no <size> specification in the dict. "<< std::endl;
				}
				ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop.");
			}
		}
  }

  if(name == "pq_coords"){
		if(params_dict.size() == 0){
			cout<<"dictionary pq_coords(dict) should be defined "<<"\n";
		} else {
			if(params_dict.count("size") == 1){
				part_atrs = new pq_coordinates(bunch,(int) params_dict["size"]);
			} else {
				if(rank_MPI == 0){
					std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(name,dict)"<< std::endl;
					std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl;
					std::cerr << "MPI size="<< size_MPI << std::endl;
					std::cerr << "MPI rank="<< rank_MPI << std::endl;
					std::cerr << "attr. name:"<< name << std::endl;
					std::cerr << "There is no <size> specification in the dict. "<< std::endl;
				}
				ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop.");
			}
		}
  }

  if(name == "part_time"){
		if(params_dict.size() == 0){
			cout<<"dictionary prf_time(dict) should be defined "<<"\n";
		} else {
			if(params_dict.count("size") == 1){
				part_atrs = new part_time(bunch, (int)params_dict["size"]);
			} else {
				if(rank_MPI == 0){
					std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(name,dict)"<< std::endl;
					std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl;
					std::cerr << "MPI size="<< size_MPI << std::endl;
					std::cerr << "MPI rank="<< rank_MPI << std::endl;
					std::cerr << "attr. name:"<< name << std::endl;
					std::cerr << "There is no <size> specification in the dict. "<< std::endl;
				}
				ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop.");
			}
		}
  }

  if(name == "Evolution"){
		if(params_dict.size() == 0){
			cout<<"dictionary Evolution(dict) should be defined "<<"\n";
		} else {
			if(params_dict.count("size") == 1){
				part_atrs = new Evolution(bunch, (int) params_dict["size"]);
			} else {
				if(rank_MPI == 0){
					std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(name,dict)"<< std::endl;
					std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl;
					std::cerr << "MPI size="<< size_MPI << std::endl;
					std::cerr << "MPI rank="<< rank_MPI << std::endl;
					std::cerr << "attr. name:"<< name << std::endl;
					std::cerr << "There is no <size> specification in the dict. "<< std::endl;
				}
				ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop.");
			}
		}
  }

  if(part_atrs == NULL) {
    if(rank_MPI == 0){
      std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(const string name, Bunch* bunch)"<< std::endl;
			std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl;
			std::cerr << "MPI size="<< size_MPI << std::endl;
			std::cerr << "MPI rank="<< rank_MPI << std::endl;
      std::cerr << "There is not a particle attirubutes class with such name in the Factory."<< std::endl;
      std::cerr << "attr. name:"<< name << std::endl;
    }
    ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop.");
    return part_atrs;
  }

	//copy the particle attributes dictionary
	part_atrs->parameterDict = params_dict;
	part_atrs->parameterDict["size"] = part_atrs->getAttSize();

  return part_atrs;
}

void ParticleAttributesFactory::getParticleAttributesNames(std::vector<string>& names){
  names.clear();
  names.push_back("macrosize");
  names.push_back("Amplitudes");
  names.push_back("Populations");
  names.push_back("pq_coords");
  names.push_back("part_time");
  names.push_back("Evolution");
  names.push_back("LostParticleAttributes");
}

<commit_msg>Added tune attributes.<commit_after>//////////////////////////////// -*- C++ -*- /////////////////////////////
//
// FILE NAME
//   ParticleAttributesFactory.cc
//
// AUTHOR
//    A. Shishlo
//
// CREATED
//    07/16/2005
//
// DESCRIPTION
//    A factory class for particle attributes classes.
//    Usually it will be used from a Bunch class instance.
//
///////////////////////////////////////////////////////////////////////////

#include "ParticleAttributesFactory.hh"

#include "ParticleMacroSize.hh"
#include "WaveFunctionAmplitudes.hh"
#include "AtomPopulations.hh"
#include "pq_coordinates.hh"
#include "part_time.hh"
#include "Evolution.hh"
#include "LostParticleAttributes.hh"
#include "ParticlePhaseAttributes.hh"

ParticleAttributesFactory::ParticleAttributesFactory()
{
}

ParticleAttributesFactory::~ParticleAttributesFactory()
{
}

ParticleAttributes* ParticleAttributesFactory::getParticleAttributesInstance(
	const string name,
	std::map<std::string,double> params_dict,
	Bunch* bunch)
{
	//for MPI --- start
	int rank_MPI = 0;
	int size_MPI = 1;
	int iMPIini  = 0;
	MPI_Comm MPI_COMM_Local = bunch->getMPI_Comm_Local()->comm;
	ORBIT_MPI_Initialized(&iMPIini);

	if(iMPIini > 0){
		ORBIT_MPI_Comm_size(MPI_COMM_Local, &size_MPI);
		ORBIT_MPI_Comm_rank(MPI_COMM_Local, &rank_MPI);
	}
	//for MPI --- stop

	ParticleAttributes* part_atrs = NULL;
	if(name == "empty"){
		part_atrs = new ParticleAttributes(bunch,0);
	}

	if(name == "macrosize"){
		part_atrs = new ParticleMacroSize(bunch);
	}

	if(name == "LostParticleAttributes"){
		part_atrs = new LostParticleAttributes(bunch);
	}

	if(name == "ParticlePhaseAttributes"){
		part_atrs = new ParticlePhaseAttributes(bunch);
	}

	if(name == "Amplitudes"){
		if(params_dict.size() == 0){
			cout<<"dictionary Amplitudes(dict) should be defined "<<"\n";
		} else {
			if(params_dict.count("size") == 1){
				part_atrs = new WaveFunctionAmplitudes(bunch,(int) params_dict["size"]);
			} else {
				if(rank_MPI == 0){
					std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(name,dict)"<< std::endl;
					std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl;
					std::cerr << "MPI size="<< size_MPI << std::endl;
					std::cerr << "MPI rank="<< rank_MPI << std::endl;
					std::cerr << "attr. name:"<< name << std::endl;
					std::cerr << "There is no <size> specification in the dict. "<< std::endl;
				}
				ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop.");
			}
		}
	}

	if(name == "Populations"){
		if(params_dict.size() == 0){
			cout<<"dictionary AtomPopulations(dict) should be defined "<<"\n";
		} else {
			if(params_dict.count("size") == 1){
				part_atrs = new AtomPopulations(bunch,(int) params_dict["size"]);
			} else {
				if(rank_MPI == 0){
					std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(name,dict)"<< std::endl;
					std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl;
					std::cerr << "MPI size="<< size_MPI << std::endl;
					std::cerr << "MPI rank="<< rank_MPI << std::endl;
					std::cerr << "attr. name:"<< name << std::endl;
					std::cerr << "There is no <size> specification in the dict. "<< std::endl;
				}
				ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop.");
			}
		}
	}

	if(name == "pq_coords"){
		if(params_dict.size() == 0){
			cout<<"dictionary pq_coords(dict) should be defined "<<"\n";
		} else {
			if(params_dict.count("size") == 1){
				part_atrs = new pq_coordinates(bunch,(int) params_dict["size"]);
			} else {
				if(rank_MPI == 0){
					std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(name,dict)"<< std::endl;
					std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl;
					std::cerr << "MPI size="<< size_MPI << std::endl;
					std::cerr << "MPI rank="<< rank_MPI << std::endl;
					std::cerr << "attr. name:"<< name << std::endl;
					std::cerr << "There is no <size> specification in the dict. "<< std::endl;
				}
				ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop.");
			}
		}
	}

	if(name == "part_time"){
		if(params_dict.size() == 0){
			cout<<"dictionary prf_time(dict) should be defined "<<"\n";
		} else {
			if(params_dict.count("size") == 1){
				part_atrs = new part_time(bunch, (int)params_dict["size"]);
			} else {
				if(rank_MPI == 0){
					std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(name,dict)"<< std::endl;
					std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl;
					std::cerr << "MPI size="<< size_MPI << std::endl;
					std::cerr << "MPI rank="<< rank_MPI << std::endl;
					std::cerr << "attr. name:"<< name << std::endl;
					std::cerr << "There is no <size> specification in the dict. "<< std::endl;
				}
				ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop.");
			}
		}
	}

	if(name == "Evolution"){
		if(params_dict.size() == 0){
			cout<<"dictionary Evolution(dict) should be defined "<<"\n";
		} else {
			if(params_dict.count("size") == 1){
				part_atrs = new Evolution(bunch, (int) params_dict["size"]);
			} else {
				if(rank_MPI == 0){
					std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(name,dict)"<< std::endl;
					std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl;
					std::cerr << "MPI size="<< size_MPI << std::endl;
					std::cerr << "MPI rank="<< rank_MPI << std::endl;
					std::cerr << "attr. name:"<< name << std::endl;
					std::cerr << "There is no <size> specification in the dict. "<< std::endl;
				}
				ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop.");
			}
		}
	}

	if(part_atrs == NULL) {
		if(rank_MPI == 0){
			std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(const string name, Bunch* bunch)"<< std::endl;
			std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl;
			std::cerr << "MPI size="<< size_MPI << std::endl;
			std::cerr << "MPI rank="<< rank_MPI << std::endl;
			std::cerr << "There is not a particle attirubutes class with such name in the Factory."<< std::endl;
			std::cerr << "attr. name:"<< name << std::endl;
		}
		ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop.");
		return part_atrs;
	}

	//copy the particle attributes dictionary
	part_atrs->parameterDict = params_dict;
	part_atrs->parameterDict["size"] = part_atrs->getAttSize();

	return part_atrs;
}

void ParticleAttributesFactory::getParticleAttributesNames(std::vector<string>& names){
	names.clear();
	names.push_back("macrosize");
	names.push_back("Amplitudes");
	names.push_back("Populations");
	names.push_back("pq_coords");
	names.push_back("part_time");
	names.push_back("Evolution");
	names.push_back("LostParticleAttributes");
	names.push_back("ParticlePhaseAttributes");
}

<|endoftext|>


<commit_before>//
//  Configurable.h
//  Clock Signal
//
//  Created by Thomas Harte on 17/11/2017.
//  Copyright © 2017 Thomas Harte. All rights reserved.
//

#ifndef Configurable_h
#define Configurable_h

#include <map>
#include <string>
#include <vector>

namespace Configurable {

/*!
	The Option class hierarchy provides a way for components, machines, etc, to provide a named
	list of typed options to which they can respond.
*/
struct Option {
	std::string long_name;
	std::string short_name;
	virtual ~Option() {}

	Option(const std::string &long_name, const std::string &short_name) : long_name(long_name), short_name(short_name) {}
};

struct BooleanOption: public Option {
	BooleanOption(const std::string &long_name, const std::string &short_name) : Option(long_name, short_name) {}
};

struct ListOption: public Option {
	std::vector<std::string> options;
	ListOption(const std::string &long_name, const std::string &short_name, const std::vector<std::string> &options) : Option(long_name, short_name), options(options) {}
};

/*!
	Selections are responses to Options.
*/
struct Selection {
	virtual ~Selection() {}
};

struct BooleanSelection: public Selection {
	bool value;
	BooleanSelection(bool value) : value(value) {}
};

struct ListSelection: public Selection {
	std::string value;
	ListSelection(const std::string value) : value(value) {}
};

using SelectionSet = std::map<std::string, std::unique_ptr<Selection>>;

/*!
	A Configuratble provides the options that it responds to and allows selections to be set.
*/
struct Device {
	virtual std::vector<std::unique_ptr<Option>> get_options() = 0;
	virtual void set_selections(const SelectionSet &selection_by_option) = 0;
	virtual SelectionSet get_accurate_selections() = 0;
	virtual SelectionSet get_user_friendly_selections() = 0;
};

template <typename T> T *selection(const Configurable::SelectionSet &selections_by_option, const std::string &name) {
	auto selection = selections_by_option.find(name);
	if(selection == selections_by_option.end()) return nullptr;
	return dynamic_cast<T *>(selection->second.get());
}

}

#endif /* Configurable_h */
<commit_msg>Adds missing #include.<commit_after>//
//  Configurable.h
//  Clock Signal
//
//  Created by Thomas Harte on 17/11/2017.
//  Copyright © 2017 Thomas Harte. All rights reserved.
//

#ifndef Configurable_h
#define Configurable_h

#include <map>
#include <memory>
#include <string>
#include <vector>

namespace Configurable {

/*!
	The Option class hierarchy provides a way for components, machines, etc, to provide a named
	list of typed options to which they can respond.
*/
struct Option {
	std::string long_name;
	std::string short_name;
	virtual ~Option() {}

	Option(const std::string &long_name, const std::string &short_name) : long_name(long_name), short_name(short_name) {}
};

struct BooleanOption: public Option {
	BooleanOption(const std::string &long_name, const std::string &short_name) : Option(long_name, short_name) {}
};

struct ListOption: public Option {
	std::vector<std::string> options;
	ListOption(const std::string &long_name, const std::string &short_name, const std::vector<std::string> &options) : Option(long_name, short_name), options(options) {}
};

/*!
	Selections are responses to Options.
*/
struct Selection {
	virtual ~Selection() {}
};

struct BooleanSelection: public Selection {
	bool value;
	BooleanSelection(bool value) : value(value) {}
};

struct ListSelection: public Selection {
	std::string value;
	ListSelection(const std::string value) : value(value) {}
};

using SelectionSet = std::map<std::string, std::unique_ptr<Selection>>;

/*!
	A Configuratble provides the options that it responds to and allows selections to be set.
*/
struct Device {
	virtual std::vector<std::unique_ptr<Option>> get_options() = 0;
	virtual void set_selections(const SelectionSet &selection_by_option) = 0;
	virtual SelectionSet get_accurate_selections() = 0;
	virtual SelectionSet get_user_friendly_selections() = 0;
};

template <typename T> T *selection(const Configurable::SelectionSet &selections_by_option, const std::string &name) {
	auto selection = selections_by_option.find(name);
	if(selection == selections_by_option.end()) return nullptr;
	return dynamic_cast<T *>(selection->second.get());
}

}

#endif /* Configurable_h */
<|endoftext|>


<commit_before>/*
* Global PRNG
* (C) 2008-2010 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/

#include <botan/libstate.h>
#include <botan/mutex.h>

#if defined(BOTAN_HAS_RANDPOOL)
  #include <botan/randpool.h>
#endif

#if defined(BOTAN_HAS_HMAC_RNG)
  #include <botan/hmac_rng.h>
#endif

#if defined(BOTAN_HAS_X931_RNG)
  #include <botan/x931_rng.h>
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_HIGH_RESOLUTION_TIMER)
  #include <botan/internal/hres_timer.h>
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_DEV_RANDOM)
  #include <botan/internal/dev_random.h>
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_EGD)
  #include <botan/internal/es_egd.h>
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_UNIX)
  #include <botan/internal/es_unix.h>
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_BEOS)
  #include <botan/internal/es_beos.h>
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_CAPI)
  #include <botan/internal/es_capi.h>
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_WIN32)
  #include <botan/internal/es_win32.h>
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_FTW)
  #include <botan/internal/es_ftw.h>
#endif

namespace Botan {

namespace {

/**
* Add any known entropy sources to this RNG
*/
void add_entropy_sources(RandomNumberGenerator* rng)
   {
#if defined(BOTAN_HAS_ENTROPY_SRC_HIGH_RESOLUTION_TIMER)
   rng->add_entropy_source(new High_Resolution_Timestamp);
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_DEV_RANDOM)
   rng->add_entropy_source(
      new Device_EntropySource(
         split_on("/dev/urandom:/dev/random:/dev/srandom", ':')
         )
      );
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_EGD)
   rng->add_entropy_source(
      new EGD_EntropySource(split_on("/var/run/egd-pool:/dev/egd-pool", ':'))
      );
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_CAPI)
   rng->add_entropy_source(new Win32_CAPI_EntropySource);
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_FTW)
   rng->add_entropy_source(new FTW_EntropySource("/proc"));
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_WIN32)
   rng->add_entropy_source(new Win32_EntropySource);
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_BEOS)
   rng->add_entropy_source(new BeOS_EntropySource);
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_UNIX)
   rng->add_entropy_source(
      new Unix_EntropySource(split_on("/bin:/sbin:/usr/bin:/usr/sbin", ':'))
      );
#endif
   }

class Serialized_PRNG : public RandomNumberGenerator
   {
   public:
      void randomize(byte out[], u32bit len)
         {
         Mutex_Holder lock(mutex);
         rng->randomize(out, len);
         }

      bool is_seeded() const
         {
         Mutex_Holder lock(mutex);
         return rng->is_seeded();
         }

      void clear()
         {
         Mutex_Holder lock(mutex);
         rng->clear();
         }

      std::string name() const
         {
         Mutex_Holder lock(mutex);
         return rng->name();
         }

      void reseed(u32bit poll_bits)
         {
         Mutex_Holder lock(mutex);
         rng->reseed(poll_bits);
         }

      void add_entropy_source(EntropySource* es)
         {
         Mutex_Holder lock(mutex);
         rng->add_entropy_source(es);
         }

      void add_entropy(const byte in[], u32bit len)
         {
         Mutex_Holder lock(mutex);
         rng->add_entropy(in, len);
         }

      // We do not own the mutex; Library_State does
      Serialized_PRNG(RandomNumberGenerator* r, Mutex* m) :
         mutex(m), rng(r) {}

      ~Serialized_PRNG() { delete rng; }
   private:
      Mutex* mutex;
      RandomNumberGenerator* rng;
   };

}

RandomNumberGenerator* Library_State::make_global_rng(Algorithm_Factory& af,
                                                      Mutex* mutex)
   {
   RandomNumberGenerator* rng = 0;

#if defined(BOTAN_HAS_HMAC_RNG)

   rng = new HMAC_RNG(af.make_mac("HMAC(SHA-512)"),
                      af.make_mac("HMAC(SHA-256)"));

#elif defined(BOTAN_HAS_RANDPOOL)

   rng = new Randpool(af.make_block_cipher("AES-256"),
                      af.make_mac("HMAC(SHA-256)"));

#endif

   if(!rng)
      throw Internal_Error("No usable RNG found enabled in build");

   /* If X9.31 is available, use it to wrap the other RNG as a failsafe */
#if defined(BOTAN_HAS_X931_RNG)

   rng = new ANSI_X931_RNG(af.make_block_cipher("AES-256"), rng);

#endif

   add_entropy_sources(rng);

   rng->reseed(256);

   return new Serialized_PRNG(rng, mutex);
   }

}
<commit_msg>mutex.h is internal - had been picking up system installed version<commit_after>/*
* Global PRNG
* (C) 2008-2010 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/

#include <botan/libstate.h>
#include <botan/internal/mutex.h>

#if defined(BOTAN_HAS_RANDPOOL)
  #include <botan/randpool.h>
#endif

#if defined(BOTAN_HAS_HMAC_RNG)
  #include <botan/hmac_rng.h>
#endif

#if defined(BOTAN_HAS_X931_RNG)
  #include <botan/x931_rng.h>
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_HIGH_RESOLUTION_TIMER)
  #include <botan/internal/hres_timer.h>
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_DEV_RANDOM)
  #include <botan/internal/dev_random.h>
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_EGD)
  #include <botan/internal/es_egd.h>
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_UNIX)
  #include <botan/internal/es_unix.h>
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_BEOS)
  #include <botan/internal/es_beos.h>
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_CAPI)
  #include <botan/internal/es_capi.h>
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_WIN32)
  #include <botan/internal/es_win32.h>
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_FTW)
  #include <botan/internal/es_ftw.h>
#endif

namespace Botan {

namespace {

/**
* Add any known entropy sources to this RNG
*/
void add_entropy_sources(RandomNumberGenerator* rng)
   {
#if defined(BOTAN_HAS_ENTROPY_SRC_HIGH_RESOLUTION_TIMER)
   rng->add_entropy_source(new High_Resolution_Timestamp);
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_DEV_RANDOM)
   rng->add_entropy_source(
      new Device_EntropySource(
         split_on("/dev/urandom:/dev/random:/dev/srandom", ':')
         )
      );
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_EGD)
   rng->add_entropy_source(
      new EGD_EntropySource(split_on("/var/run/egd-pool:/dev/egd-pool", ':'))
      );
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_CAPI)
   rng->add_entropy_source(new Win32_CAPI_EntropySource);
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_FTW)
   rng->add_entropy_source(new FTW_EntropySource("/proc"));
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_WIN32)
   rng->add_entropy_source(new Win32_EntropySource);
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_BEOS)
   rng->add_entropy_source(new BeOS_EntropySource);
#endif

#if defined(BOTAN_HAS_ENTROPY_SRC_UNIX)
   rng->add_entropy_source(
      new Unix_EntropySource(split_on("/bin:/sbin:/usr/bin:/usr/sbin", ':'))
      );
#endif
   }

class Serialized_PRNG : public RandomNumberGenerator
   {
   public:
      void randomize(byte out[], u32bit len)
         {
         Mutex_Holder lock(mutex);
         rng->randomize(out, len);
         }

      bool is_seeded() const
         {
         Mutex_Holder lock(mutex);
         return rng->is_seeded();
         }

      void clear()
         {
         Mutex_Holder lock(mutex);
         rng->clear();
         }

      std::string name() const
         {
         Mutex_Holder lock(mutex);
         return rng->name();
         }

      void reseed(u32bit poll_bits)
         {
         Mutex_Holder lock(mutex);
         rng->reseed(poll_bits);
         }

      void add_entropy_source(EntropySource* es)
         {
         Mutex_Holder lock(mutex);
         rng->add_entropy_source(es);
         }

      void add_entropy(const byte in[], u32bit len)
         {
         Mutex_Holder lock(mutex);
         rng->add_entropy(in, len);
         }

      // We do not own the mutex; Library_State does
      Serialized_PRNG(RandomNumberGenerator* r, Mutex* m) :
         mutex(m), rng(r) {}

      ~Serialized_PRNG() { delete rng; }
   private:
      Mutex* mutex;
      RandomNumberGenerator* rng;
   };

}

RandomNumberGenerator* Library_State::make_global_rng(Algorithm_Factory& af,
                                                      Mutex* mutex)
   {
   RandomNumberGenerator* rng = 0;

#if defined(BOTAN_HAS_HMAC_RNG)

   rng = new HMAC_RNG(af.make_mac("HMAC(SHA-512)"),
                      af.make_mac("HMAC(SHA-256)"));

#elif defined(BOTAN_HAS_RANDPOOL)

   rng = new Randpool(af.make_block_cipher("AES-256"),
                      af.make_mac("HMAC(SHA-256)"));

#endif

   if(!rng)
      throw Internal_Error("No usable RNG found enabled in build");

   /* If X9.31 is available, use it to wrap the other RNG as a failsafe */
#if defined(BOTAN_HAS_X931_RNG)

   rng = new ANSI_X931_RNG(af.make_block_cipher("AES-256"), rng);

#endif

   add_entropy_sources(rng);

   rng->reseed(256);

   return new Serialized_PRNG(rng, mutex);
   }

}
<|endoftext|>