<commit_before>/***********************************************************************
    filename:   CEGUIDirect3D10Renderer.cpp
    created:    Sat Mar 7 2009
    author:     Paul D Turner (parts based on code by Rajko Stojadinovic)
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/RendererModules/Direct3D10/Renderer.h"
#include "CEGUI/RendererModules/Direct3D10/GeometryBuffer.h"
#include "CEGUI/RendererModules/Direct3D10/TextureTarget.h"
#include "CEGUI/RendererModules/Direct3D10/ViewportTarget.h"
#include "CEGUI/RendererModules/Direct3D10/Texture.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/System.h"
#include "CEGUI/DefaultResourceProvider.h"
#include "CEGUI/Logger.h"
#include <algorithm>

#include "shader.txt"

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
String Direct3D10Renderer::d_rendererID(
"CEGUI::Direct3D10Renderer - Official Direct3D 10 based 2nd generation renderer"
" module.");

//----------------------------------------------------------------------------//
Direct3D10Renderer& Direct3D10Renderer::bootstrapSystem(ID3D10Device* device,
                                                        const int abi)
{
    System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME);

    if (System::getSingletonPtr())
        CEGUI_THROW(InvalidRequestException(
            "CEGUI::System object is already initialised."));

    Direct3D10Renderer& renderer(create(device));
    DefaultResourceProvider* rp = CEGUI_NEW CEGUI::DefaultResourceProvider();
    System::create(renderer, rp);

    return renderer;
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::destroySystem()
{
    System* sys;
    if (!(sys = System::getSingletonPtr()))
        CEGUI_THROW(InvalidRequestException(
            "CEGUI::System object is not created or was already destroyed."));

    Direct3D10Renderer* renderer =
        static_cast<Direct3D10Renderer*>(sys->getRenderer());
    DefaultResourceProvider* rp =
        static_cast<DefaultResourceProvider*>(sys->getResourceProvider());

    System::destroy();
    delete rp;
    destroy(*renderer);
}

//----------------------------------------------------------------------------//
Direct3D10Renderer& Direct3D10Renderer::create(ID3D10Device* device,
                                               const int abi)
{
    System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME);

    return *new Direct3D10Renderer(device);
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::destroy(Direct3D10Renderer& renderer)
{
    delete &renderer;
}

//----------------------------------------------------------------------------//
RenderTarget& Direct3D10Renderer::getDefaultRenderTarget()
{
    return *d_defaultTarget;
}

//----------------------------------------------------------------------------//
GeometryBuffer& Direct3D10Renderer::createGeometryBuffer()
{
    Direct3D10GeometryBuffer* b = new Direct3D10GeometryBuffer(*this);
    d_geometryBuffers.push_back(b);
    return *b;
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::destroyGeometryBuffer(const GeometryBuffer& buffer)
{
    GeometryBufferList::iterator i = std::find(d_geometryBuffers.begin(),
                                               d_geometryBuffers.end(),
                                               &buffer);

    if (d_geometryBuffers.end() != i)
    {
        d_geometryBuffers.erase(i);
        delete &buffer;
    }
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::destroyAllGeometryBuffers()
{
    while (!d_geometryBuffers.empty())
        destroyGeometryBuffer(**d_geometryBuffers.begin());
}

//----------------------------------------------------------------------------//
TextureTarget* Direct3D10Renderer::createTextureTarget()
{
    TextureTarget* t = new Direct3D10TextureTarget(*this);
    d_textureTargets.push_back(t);
    return t;
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::destroyTextureTarget(TextureTarget* target)
{
    TextureTargetList::iterator i = std::find(d_textureTargets.begin(),
                                              d_textureTargets.end(),
                                              target);

    if (d_textureTargets.end() != i)
    {
        d_textureTargets.erase(i);
        delete target;
    }
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::destroyAllTextureTargets()
{
    while (!d_textureTargets.empty())
        destroyTextureTarget(*d_textureTargets.begin());
}

//----------------------------------------------------------------------------//
Texture& Direct3D10Renderer::createTexture(const String& name)
{
    throwIfNameExists(name);

    Direct3D10Texture* tex = new Direct3D10Texture(*d_device, name);
    d_textures[name] = tex;

    logTextureCreation(name);

    return *tex;
}

//----------------------------------------------------------------------------//
Texture& Direct3D10Renderer::createTexture(const String& name,
                                           const String& filename,
                                           const String& resourceGroup)
{
    throwIfNameExists(name);

    Direct3D10Texture* tex = new Direct3D10Texture(*d_device, name, filename,
                                                   resourceGroup);
    d_textures[name] = tex;

    logTextureCreation(name);

    return *tex;
}

//----------------------------------------------------------------------------//
Texture& Direct3D10Renderer::createTexture(const String& name,
                                           const Sizef& size)
{
    throwIfNameExists(name);

    Direct3D10Texture* tex = new Direct3D10Texture(*d_device, name, size);
    d_textures[name] = tex;

    logTextureCreation(name);

    return *tex;
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::throwIfNameExists(const String& name) const
{
    if (d_textures.find(name) != d_textures.end())
        CEGUI_THROW(AlreadyExistsException(
            "[Direct3D10Renderer] Texture already exists: " + name));
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::logTextureCreation(const String& name)
{
    Logger* logger = Logger::getSingletonPtr();
    if (logger)
        logger->logEvent("[Direct3D10Renderer] Created texture: " + name);
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::destroyTexture(Texture& texture)
{
    destroyTexture(texture.getName());
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::destroyTexture(const String& name)
{
    TextureMap::iterator i = d_textures.find(name);

    if (d_textures.end() != i)
    {
        logTextureDestruction(name);
        delete i->second;
        d_textures.erase(i);
    }
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::logTextureDestruction(const String& name)
{
    Logger* logger = Logger::getSingletonPtr();
    if (logger)
        logger->logEvent("[Direct3D10Renderer] Destroyed texture: " + name);
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::destroyAllTextures()
{
    while (!d_textures.empty())
        destroyTexture(d_textures.begin()->first);
}

//----------------------------------------------------------------------------//
Texture& Direct3D10Renderer::getTexture(const String& name) const
{
    TextureMap::const_iterator i = d_textures.find(name);

    if (i == d_textures.end())
        CEGUI_THROW(UnknownObjectException("Texture does not exist: " + name));

    return *i->second;
}

//----------------------------------------------------------------------------//
bool Direct3D10Renderer::isTextureDefined(const String& name) const
{
    return d_textures.find(name) != d_textures.end();
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::beginRendering()
{
    d_device->IASetInputLayout(d_inputLayout);
    d_device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::endRendering()
{
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::setDisplaySize(const Sizef& sz)
{
    if (sz != d_displaySize)
    {
        d_displaySize = sz;

        // FIXME: This is probably not the right thing to do in all cases.
        Rectf area(d_defaultTarget->getArea());
        area.setSize(sz);
        d_defaultTarget->setArea(area);
    }

}

//----------------------------------------------------------------------------//
const Sizef& Direct3D10Renderer::getDisplaySize() const
{
    return d_displaySize;
}

//----------------------------------------------------------------------------//
const Vector2f& Direct3D10Renderer::getDisplayDPI() const
{
    return d_displayDPI;
}

//----------------------------------------------------------------------------//
uint Direct3D10Renderer::getMaxTextureSize() const
{
    return 8192;
}

//----------------------------------------------------------------------------//
const String& Direct3D10Renderer::getIdentifierString() const
{
    return d_rendererID;
}

//----------------------------------------------------------------------------//
Direct3D10Renderer::Direct3D10Renderer(ID3D10Device* device) :
    d_device(device),
    d_displaySize(getViewportSize()),
    d_displayDPI(96, 96),
    d_defaultTarget(0),
    d_effect(0),
    d_normalClippedTechnique(0),
    d_normalUnclippedTechnique(0),
    d_premultipliedClippedTechnique(0),
    d_premultipliedUnclippedTechnique(0),
    d_inputLayout(0),
    d_boundTextureVariable(0),
    d_worldMatrixVariable(0),
    d_projectionMatrixVariable(0)
{
    // create the main effect from the shader source.
    ID3D10Blob* errors = 0;
    if (FAILED(D3DX10CreateEffectFromMemory(shaderSource, sizeof(shaderSource),
                                            0, 0, 0, "fx_4_0", 0, 0, d_device,
                                            0, 0, &d_effect, &errors, 0)))
    {
        std::string msg(static_cast<const char*>(errors->GetBufferPointer()),
                        errors->GetBufferSize());
        errors->Release();
        CEGUI_THROW(RendererException(msg));
    }

    // extract the rendering techniques
    d_normalClippedTechnique =
            d_effect->GetTechniqueByName("BM_NORMAL_Clipped_Rendering");
    d_normalUnclippedTechnique =
            d_effect->GetTechniqueByName("BM_NORMAL_Unclipped_Rendering");
    d_premultipliedClippedTechnique =
            d_effect->GetTechniqueByName("BM_RTT_PREMULTIPLIED_Clipped_Rendering");
    d_premultipliedClippedTechnique =
            d_effect->GetTechniqueByName("BM_RTT_PREMULTIPLIED_Unclipped_Rendering");

    // Get the variables from the shader we need to be able to access
    d_boundTextureVariable =
            d_effect->GetVariableByName("BoundTexture")->AsShaderResource();
    d_worldMatrixVariable =
            d_effect->GetVariableByName("WorldMatrix")->AsMatrix();
    d_projectionMatrixVariable =
            d_effect->GetVariableByName("ProjectionMatrix")->AsMatrix();

    // Create the input layout
    const D3D10_INPUT_ELEMENT_DESC vertex_layout[] =
    {
        { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,  0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
        { "COLOR",    0, DXGI_FORMAT_R8G8B8A8_UNORM,  0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 },
        { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT,	  0, 16, D3D10_INPUT_PER_VERTEX_DATA, 0 },
    };

    const UINT element_count = sizeof(vertex_layout) / sizeof(vertex_layout[0]);

    D3D10_PASS_DESC pass_desc;
    if (FAILED(d_normalClippedTechnique->GetPassByIndex(0)->GetDesc(&pass_desc)))
        CEGUI_THROW(RendererException(
            "failed to obtain technique description for pass 0."));

    if (FAILED(d_device->CreateInputLayout(vertex_layout, element_count,
                                            pass_desc.pIAInputSignature,
                                            pass_desc.IAInputSignatureSize,
                                            &d_inputLayout)))
    {
        CEGUI_THROW(RendererException("failed to create D3D 10 input layout."));
    }

    d_defaultTarget = new Direct3D10ViewportTarget(*this);
}

//----------------------------------------------------------------------------//
Direct3D10Renderer::~Direct3D10Renderer()
{
    destroyAllTextureTargets();
    destroyAllTextures();
    destroyAllGeometryBuffers();

    delete d_defaultTarget;

    if (d_effect)
        d_effect->Release();

    if (d_inputLayout)
        d_inputLayout->Release();

}

//----------------------------------------------------------------------------//
Sizef Direct3D10Renderer::getViewportSize()
{
    D3D10_VIEWPORT vp;
    UINT vp_count = 1;

    d_device->RSGetViewports(&vp_count, &vp);

    if (vp_count != 1)
        CEGUI_THROW(RendererException(
            "Unable to access required view port information from "
            "IDirect3DDevice10."));
    else
        return Sizef(static_cast<float>(vp.Width),
                      static_cast<float>(vp.Height));
}

//----------------------------------------------------------------------------//
ID3D10Device& Direct3D10Renderer::getDirect3DDevice() const
{
    return *d_device;
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::bindTechniquePass(const BlendMode mode,
                                           const bool clipped)
{
    if (mode == BM_RTT_PREMULTIPLIED)
        if (clipped)
            d_premultipliedClippedTechnique->GetPassByIndex(0)->Apply(0);
        else
            d_premultipliedUnclippedTechnique->GetPassByIndex(0)->Apply(0);
    else if (clipped)
        d_normalClippedTechnique->GetPassByIndex(0)->Apply(0);
    else
        d_normalUnclippedTechnique->GetPassByIndex(0)->Apply(0);
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::setCurrentTextureShaderResource(
    ID3D10ShaderResourceView* srv)
{
    d_boundTextureVariable->SetResource(srv);
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::setProjectionMatrix(D3DXMATRIX& matrix)
{
    d_projectionMatrixVariable->SetMatrix(reinterpret_cast<float*>(&matrix));
}
//----------------------------------------------------------------------------//
void Direct3D10Renderer::setWorldMatrix(D3DXMATRIX& matrix)
{
    d_worldMatrixVariable->SetMatrix(reinterpret_cast<float*>(&matrix));
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section
<commit_msg>FIX: CEGUI_NEW used without including the headers for that - changed to new Changed it like it is in D3D9 and -11<commit_after>/***********************************************************************
    filename:   CEGUIDirect3D10Renderer.cpp
    created:    Sat Mar 7 2009
    author:     Paul D Turner (parts based on code by Rajko Stojadinovic)
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/RendererModules/Direct3D10/Renderer.h"
#include "CEGUI/RendererModules/Direct3D10/GeometryBuffer.h"
#include "CEGUI/RendererModules/Direct3D10/TextureTarget.h"
#include "CEGUI/RendererModules/Direct3D10/ViewportTarget.h"
#include "CEGUI/RendererModules/Direct3D10/Texture.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/System.h"
#include "CEGUI/DefaultResourceProvider.h"
#include "CEGUI/Logger.h"
#include <algorithm>

#include "shader.txt"

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
String Direct3D10Renderer::d_rendererID(
"CEGUI::Direct3D10Renderer - Official Direct3D 10 based 2nd generation renderer"
" module.");

//----------------------------------------------------------------------------//
Direct3D10Renderer& Direct3D10Renderer::bootstrapSystem(ID3D10Device* device,
                                                        const int abi)
{
    System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME);

    if (System::getSingletonPtr())
        CEGUI_THROW(InvalidRequestException(
            "CEGUI::System object is already initialised."));

    Direct3D10Renderer& renderer(create(device));
    DefaultResourceProvider* rp = new CEGUI::DefaultResourceProvider();
    System::create(renderer, rp);

    return renderer;
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::destroySystem()
{
    System* sys;
    if (!(sys = System::getSingletonPtr()))
        CEGUI_THROW(InvalidRequestException(
            "CEGUI::System object is not created or was already destroyed."));

    Direct3D10Renderer* renderer =
        static_cast<Direct3D10Renderer*>(sys->getRenderer());
    DefaultResourceProvider* rp =
        static_cast<DefaultResourceProvider*>(sys->getResourceProvider());

    System::destroy();
    delete rp;
    destroy(*renderer);
}

//----------------------------------------------------------------------------//
Direct3D10Renderer& Direct3D10Renderer::create(ID3D10Device* device,
                                               const int abi)
{
    System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME);

    return *new Direct3D10Renderer(device);
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::destroy(Direct3D10Renderer& renderer)
{
    delete &renderer;
}

//----------------------------------------------------------------------------//
RenderTarget& Direct3D10Renderer::getDefaultRenderTarget()
{
    return *d_defaultTarget;
}

//----------------------------------------------------------------------------//
GeometryBuffer& Direct3D10Renderer::createGeometryBuffer()
{
    Direct3D10GeometryBuffer* b = new Direct3D10GeometryBuffer(*this);
    d_geometryBuffers.push_back(b);
    return *b;
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::destroyGeometryBuffer(const GeometryBuffer& buffer)
{
    GeometryBufferList::iterator i = std::find(d_geometryBuffers.begin(),
                                               d_geometryBuffers.end(),
                                               &buffer);

    if (d_geometryBuffers.end() != i)
    {
        d_geometryBuffers.erase(i);
        delete &buffer;
    }
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::destroyAllGeometryBuffers()
{
    while (!d_geometryBuffers.empty())
        destroyGeometryBuffer(**d_geometryBuffers.begin());
}

//----------------------------------------------------------------------------//
TextureTarget* Direct3D10Renderer::createTextureTarget()
{
    TextureTarget* t = new Direct3D10TextureTarget(*this);
    d_textureTargets.push_back(t);
    return t;
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::destroyTextureTarget(TextureTarget* target)
{
    TextureTargetList::iterator i = std::find(d_textureTargets.begin(),
                                              d_textureTargets.end(),
                                              target);

    if (d_textureTargets.end() != i)
    {
        d_textureTargets.erase(i);
        delete target;
    }
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::destroyAllTextureTargets()
{
    while (!d_textureTargets.empty())
        destroyTextureTarget(*d_textureTargets.begin());
}

//----------------------------------------------------------------------------//
Texture& Direct3D10Renderer::createTexture(const String& name)
{
    throwIfNameExists(name);

    Direct3D10Texture* tex = new Direct3D10Texture(*d_device, name);
    d_textures[name] = tex;

    logTextureCreation(name);

    return *tex;
}

//----------------------------------------------------------------------------//
Texture& Direct3D10Renderer::createTexture(const String& name,
                                           const String& filename,
                                           const String& resourceGroup)
{
    throwIfNameExists(name);

    Direct3D10Texture* tex = new Direct3D10Texture(*d_device, name, filename,
                                                   resourceGroup);
    d_textures[name] = tex;

    logTextureCreation(name);

    return *tex;
}

//----------------------------------------------------------------------------//
Texture& Direct3D10Renderer::createTexture(const String& name,
                                           const Sizef& size)
{
    throwIfNameExists(name);

    Direct3D10Texture* tex = new Direct3D10Texture(*d_device, name, size);
    d_textures[name] = tex;

    logTextureCreation(name);

    return *tex;
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::throwIfNameExists(const String& name) const
{
    if (d_textures.find(name) != d_textures.end())
        CEGUI_THROW(AlreadyExistsException(
            "[Direct3D10Renderer] Texture already exists: " + name));
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::logTextureCreation(const String& name)
{
    Logger* logger = Logger::getSingletonPtr();
    if (logger)
        logger->logEvent("[Direct3D10Renderer] Created texture: " + name);
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::destroyTexture(Texture& texture)
{
    destroyTexture(texture.getName());
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::destroyTexture(const String& name)
{
    TextureMap::iterator i = d_textures.find(name);

    if (d_textures.end() != i)
    {
        logTextureDestruction(name);
        delete i->second;
        d_textures.erase(i);
    }
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::logTextureDestruction(const String& name)
{
    Logger* logger = Logger::getSingletonPtr();
    if (logger)
        logger->logEvent("[Direct3D10Renderer] Destroyed texture: " + name);
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::destroyAllTextures()
{
    while (!d_textures.empty())
        destroyTexture(d_textures.begin()->first);
}

//----------------------------------------------------------------------------//
Texture& Direct3D10Renderer::getTexture(const String& name) const
{
    TextureMap::const_iterator i = d_textures.find(name);

    if (i == d_textures.end())
        CEGUI_THROW(UnknownObjectException("Texture does not exist: " + name));

    return *i->second;
}

//----------------------------------------------------------------------------//
bool Direct3D10Renderer::isTextureDefined(const String& name) const
{
    return d_textures.find(name) != d_textures.end();
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::beginRendering()
{
    d_device->IASetInputLayout(d_inputLayout);
    d_device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::endRendering()
{
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::setDisplaySize(const Sizef& sz)
{
    if (sz != d_displaySize)
    {
        d_displaySize = sz;

        // FIXME: This is probably not the right thing to do in all cases.
        Rectf area(d_defaultTarget->getArea());
        area.setSize(sz);
        d_defaultTarget->setArea(area);
    }

}

//----------------------------------------------------------------------------//
const Sizef& Direct3D10Renderer::getDisplaySize() const
{
    return d_displaySize;
}

//----------------------------------------------------------------------------//
const Vector2f& Direct3D10Renderer::getDisplayDPI() const
{
    return d_displayDPI;
}

//----------------------------------------------------------------------------//
uint Direct3D10Renderer::getMaxTextureSize() const
{
    return 8192;
}

//----------------------------------------------------------------------------//
const String& Direct3D10Renderer::getIdentifierString() const
{
    return d_rendererID;
}

//----------------------------------------------------------------------------//
Direct3D10Renderer::Direct3D10Renderer(ID3D10Device* device) :
    d_device(device),
    d_displaySize(getViewportSize()),
    d_displayDPI(96, 96),
    d_defaultTarget(0),
    d_effect(0),
    d_normalClippedTechnique(0),
    d_normalUnclippedTechnique(0),
    d_premultipliedClippedTechnique(0),
    d_premultipliedUnclippedTechnique(0),
    d_inputLayout(0),
    d_boundTextureVariable(0),
    d_worldMatrixVariable(0),
    d_projectionMatrixVariable(0)
{
    // create the main effect from the shader source.
    ID3D10Blob* errors = 0;
    if (FAILED(D3DX10CreateEffectFromMemory(shaderSource, sizeof(shaderSource),
                                            0, 0, 0, "fx_4_0", 0, 0, d_device,
                                            0, 0, &d_effect, &errors, 0)))
    {
        std::string msg(static_cast<const char*>(errors->GetBufferPointer()),
                        errors->GetBufferSize());
        errors->Release();
        CEGUI_THROW(RendererException(msg));
    }

    // extract the rendering techniques
    d_normalClippedTechnique =
            d_effect->GetTechniqueByName("BM_NORMAL_Clipped_Rendering");
    d_normalUnclippedTechnique =
            d_effect->GetTechniqueByName("BM_NORMAL_Unclipped_Rendering");
    d_premultipliedClippedTechnique =
            d_effect->GetTechniqueByName("BM_RTT_PREMULTIPLIED_Clipped_Rendering");
    d_premultipliedClippedTechnique =
            d_effect->GetTechniqueByName("BM_RTT_PREMULTIPLIED_Unclipped_Rendering");

    // Get the variables from the shader we need to be able to access
    d_boundTextureVariable =
            d_effect->GetVariableByName("BoundTexture")->AsShaderResource();
    d_worldMatrixVariable =
            d_effect->GetVariableByName("WorldMatrix")->AsMatrix();
    d_projectionMatrixVariable =
            d_effect->GetVariableByName("ProjectionMatrix")->AsMatrix();

    // Create the input layout
    const D3D10_INPUT_ELEMENT_DESC vertex_layout[] =
    {
        { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,  0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
        { "COLOR",    0, DXGI_FORMAT_R8G8B8A8_UNORM,  0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 },
        { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT,	  0, 16, D3D10_INPUT_PER_VERTEX_DATA, 0 },
    };

    const UINT element_count = sizeof(vertex_layout) / sizeof(vertex_layout[0]);

    D3D10_PASS_DESC pass_desc;
    if (FAILED(d_normalClippedTechnique->GetPassByIndex(0)->GetDesc(&pass_desc)))
        CEGUI_THROW(RendererException(
            "failed to obtain technique description for pass 0."));

    if (FAILED(d_device->CreateInputLayout(vertex_layout, element_count,
                                            pass_desc.pIAInputSignature,
                                            pass_desc.IAInputSignatureSize,
                                            &d_inputLayout)))
    {
        CEGUI_THROW(RendererException("failed to create D3D 10 input layout."));
    }

    d_defaultTarget = new Direct3D10ViewportTarget(*this);
}

//----------------------------------------------------------------------------//
Direct3D10Renderer::~Direct3D10Renderer()
{
    destroyAllTextureTargets();
    destroyAllTextures();
    destroyAllGeometryBuffers();

    delete d_defaultTarget;

    if (d_effect)
        d_effect->Release();

    if (d_inputLayout)
        d_inputLayout->Release();

}

//----------------------------------------------------------------------------//
Sizef Direct3D10Renderer::getViewportSize()
{
    D3D10_VIEWPORT vp;
    UINT vp_count = 1;

    d_device->RSGetViewports(&vp_count, &vp);

    if (vp_count != 1)
        CEGUI_THROW(RendererException(
            "Unable to access required view port information from "
            "IDirect3DDevice10."));
    else
        return Sizef(static_cast<float>(vp.Width),
                      static_cast<float>(vp.Height));
}

//----------------------------------------------------------------------------//
ID3D10Device& Direct3D10Renderer::getDirect3DDevice() const
{
    return *d_device;
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::bindTechniquePass(const BlendMode mode,
                                           const bool clipped)
{
    if (mode == BM_RTT_PREMULTIPLIED)
        if (clipped)
            d_premultipliedClippedTechnique->GetPassByIndex(0)->Apply(0);
        else
            d_premultipliedUnclippedTechnique->GetPassByIndex(0)->Apply(0);
    else if (clipped)
        d_normalClippedTechnique->GetPassByIndex(0)->Apply(0);
    else
        d_normalUnclippedTechnique->GetPassByIndex(0)->Apply(0);
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::setCurrentTextureShaderResource(
    ID3D10ShaderResourceView* srv)
{
    d_boundTextureVariable->SetResource(srv);
}

//----------------------------------------------------------------------------//
void Direct3D10Renderer::setProjectionMatrix(D3DXMATRIX& matrix)
{
    d_projectionMatrixVariable->SetMatrix(reinterpret_cast<float*>(&matrix));
}
//----------------------------------------------------------------------------//
void Direct3D10Renderer::setWorldMatrix(D3DXMATRIX& matrix)
{
    d_worldMatrixVariable->SetMatrix(reinterpret_cast<float*>(&matrix));
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section
<|endoftext|>


<commit_before>#ifndef _SNARKFRONT_AES_SBOX_HPP_
#define _SNARKFRONT_AES_SBOX_HPP_

#include <array>
#include <cstdint>
#include "DSL_utility.hpp"

namespace snarkfront {

////////////////////////////////////////////////////////////////////////////////
// FIPS PUB 197, NIST November 2001
//
// Algorithm     Key Length    Block Size   Number of Rounds
//               (Nk words)    (Nb words)   (Nr)
//
// AES-128       4             4            10
// AES-192       6             4            12
// AES-256       8             4            14
//

////////////////////////////////////////////////////////////////////////////////
// S-Box
//

template <typename T, typename U, typename BITWISE>
class AES_SBox
{
public:
    AES_SBox()
        : m_lut(std::array<std::uint8_t, 256>{
            // 00
            0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5,
            0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,

            // 10
            0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
            0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,

            // 20
            0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc,
            0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,

            // 30
            0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a,
            0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,

            // 40
            0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
            0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,

            // 50
            0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,
            0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,

            // 60
            0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85,
            0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,

            // 70
            0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
            0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,

            // 80
            0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17,
            0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,

            // 90
            0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88,
            0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,

            // a0
            0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
            0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,

            // b0
            0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9,
            0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,

            // c0
            0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6,
            0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,

            // d0
            0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
            0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,

            // e0
            0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94,
            0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,

            // f0
            0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68,
            0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 })
    {}

    U operator() (const T& x) const {
        return m_lut[x];
    }

private:
    const BitwiseLUT<T, U, std::uint8_t, BITWISE>  m_lut;
};

} // namespace snarkfront

#endif
<commit_msg>scope header file paths<commit_after>#ifndef _SNARKFRONT_AES_SBOX_HPP_
#define _SNARKFRONT_AES_SBOX_HPP_

#include <array>
#include <cstdint>

#include <snarkfront/DSL_utility.hpp>

namespace snarkfront {

////////////////////////////////////////////////////////////////////////////////
// FIPS PUB 197, NIST November 2001
//
// Algorithm     Key Length    Block Size   Number of Rounds
//               (Nk words)    (Nb words)   (Nr)
//
// AES-128       4             4            10
// AES-192       6             4            12
// AES-256       8             4            14
//

////////////////////////////////////////////////////////////////////////////////
// S-Box
//

template <typename T, typename U, typename BITWISE>
class AES_SBox
{
public:
    AES_SBox()
        : m_lut(std::array<std::uint8_t, 256>{
            // 00
            0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5,
            0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,

            // 10
            0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
            0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,

            // 20
            0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc,
            0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,

            // 30
            0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a,
            0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,

            // 40
            0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
            0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,

            // 50
            0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,
            0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,

            // 60
            0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85,
            0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,

            // 70
            0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
            0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,

            // 80
            0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17,
            0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,

            // 90
            0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88,
            0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,

            // a0
            0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
            0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,

            // b0
            0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9,
            0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,

            // c0
            0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6,
            0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,

            // d0
            0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
            0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,

            // e0
            0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94,
            0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,

            // f0
            0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68,
            0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 })
    {}

    U operator() (const T& x) const {
        return m_lut[x];
    }

private:
    const BitwiseLUT<T, U, std::uint8_t, BITWISE>  m_lut;
};

} // namespace snarkfront

#endif
<|endoftext|>


<commit_before>#include <AP_Utils.h>

AP_Utils::AP_Utils(void) {

}

void AP_Utils::begin(void) {
  for(int i=0; i<16; i++) {
    servos[i].number = i;
    if((i % 2 == 0)&&(i<12)) {
      servos[i].type = HORIZONTAL;
    } else if(i==15) {
      servos[i].type = SENSOR;
    } else {
      servos[i].type = VERTICAL;
    }
  }
  #ifdef DEBUG
    Serial.print("\n[INF]\t[SETUP]\tStarting PWM ... ");
  #endif
  pwm.begin();
  #ifdef DEBUG
    Serial.println("Done!");
    Serial.print("[INF]\t[SETUP]\tSetting PWM frequency to ");
    Serial.print(PWM_FREQ);
    Serial.print(" Hz ... ");
  #endif
  pwm.setPWMFreq(PWM_FREQ);
  #ifdef DEBUG
    Serial.println("Done!");
    Serial.print("[INF]\t[SETUP]\tSetting all servos to default position ... ");
  #endif
  reset();
  #ifdef DEBUG
    Serial.println("Done!");
    Serial.println("[INF]\t[SETUP]\tSuccesfully started!");
  #endif
}

void AP_Utils::reset(void) {
  for(int i=0; i<16; i++) {
    pwm.setPWM(i, 0, pulseLength(90));
    servos[i].position = 90;
  }
  servos[15].position = 0;
}

void AP_Utils::stretchAll(void) {
  for(int i=0; i<2; i++) {
    legStretch(0, true);
    legStretch(2, true);
    legStretch(4, true);
    delay(DELAY);

    legStretch(1, true);
    legStretch(3, true);
    legStretch(5, true);
    delay(DELAY);
  }
}

void AP_Utils::walk(float dir, float distance) {

}

float AP_Utils::sr04(uint8_t trig, uint8_t echo, int unit) {
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  float duration, distance;
  digitalWrite(trig, LOW);
  delayMicroseconds(2);

  digitalWrite(trig, HIGH);
  delayMicroseconds(10);

  digitalWrite(trig, LOW);
  duration = pulseIn(echo, HIGH);

  distance = (346.3*duration*0.000001*unit)/2;

  if((distance >= 0.02*unit) && (distance <= 4*unit)) {
    #ifdef DEBUG
      Serial.print("[INF]\t[SR04]\tDistance: ");
      Serial.print(distance);
      switch(unit) {
        case MM:
          Serial.println(" mm");
          break;
        case CM:
          Serial.println(" cm");
          break;
        case M:
          Serial.println(" m");
          break;
      }
    #endif
    return(distance);
  } else {
    #ifdef DEBUG
      Serial.print("[ERROR]\t[SR04]\tDistance ");
      Serial.print(distance);
      switch(unit) {
        case MM:
          Serial.print(" mm ");
          break;
        case CM:
          Serial.print(" cm ");
          break;
        case M:
          Serial.print(" m ");
          break;
      }
      Serial.println("is out of bounds for SR04, ignoring.");
    #endif
    return -1;
  }
}

float AP_Utils::sr04_average(uint8_t trig, uint8_t echo, int unit, int samples, int time) {
  #ifdef DEBUG
    unsigned long timer = micros();
    Serial.print("[INF]\t[SR04]\tMeasuring average distance (");
    Serial.print(samples);
    Serial.print(" samples over ");
    Serial.print(time);
    Serial.println(" ms)");
  #endif
  float average, pause, value;
  float total = 0;
  if(time/samples <= 12) {
  #ifdef DEBUG
      Serial.println("[WARN]\t[SR04]\tSamples to time ratio too low, setting to default.");
  #endif
    pause = 0;
  } else {
    pause = time/samples - 12;
  }
  for(int i=0; i<samples; i++) {
    value = sr04(trig, echo, unit);
    if(value != -1) {
      total += value;
      delay(pause);
    } else {
      i--;
    }
  }
  average = total/samples;
  #ifdef DEBUG
    Serial.print("[INF]\t[SR04]\tCalculated average distance: ");
    Serial.print(average);
    switch(unit) {
      case MM:
        Serial.println(" mm");
        break;
      case CM:
        Serial.println(" cm");
        break;
      case M:
        Serial.println(" m");
        break;
    }
    Serial.print("[INF]\t[SR04]\tSampling took ");
    Serial.print((micros()-timer)/1000);
    Serial.println(" ms.");
  #endif
  return average;
}

float AP_Utils::sr04_median(uint8_t trig, uint8_t echo, int unit, int samples, int time) {
  #ifdef DEBUG
    unsigned long timer = micros();
    Serial.print("[INF]\t[SR04]\tMeasuring median distance (");
    Serial.print(samples);
    Serial.print(" samples over ");
    Serial.print(time);
    Serial.println(" ms)");
  #endif
  float med, pause, value;
  float *values;
  values = new float[samples];
  if(time/samples < 12) {
  #ifdef DEBUG
      Serial.println("[WARN]\t[SR04]\tSamples to time ratio too low, setting to default.");
  #endif
    pause = 0;
  } else {
    pause = time/samples - 12;
  }
  for(int i=0; i<samples; i++) {
    value = sr04(trig, echo, unit);
    if(value != -1) {
      values[i] = value;
      delay(pause);
    } else {
      i--;
    }
  }

  med = median(values, samples);
  delete [] values;
  #ifdef DEBUG
    Serial.print("[INF]\t[SR04]\tCalculated median distance: ");
    Serial.print(med);
    switch(unit) {
      case MM:
        Serial.println(" mm");
        break;
      case CM:
        Serial.println(" cm");
        break;
      case M:
        Serial.println(" m");
        break;
    }
    Serial.print("[INF]\t[SR04]\tSampling took ");
    Serial.print((micros()-timer)/1000);
    Serial.println(" ms.");
  #endif
  return(med);
}

int AP_Utils::pulseLength(int deg) {
  return map(deg, 0, 180, SERVOMIN, SERVOMAX);
}

void AP_Utils::pwmove(uint8_t i, int deg) {
  pwm.setPWM(i, 0, pulseLength(deg));
  servos[i].position = deg;
  delay(DELAY);
}

void AP_Utils::legUp(uint8_t leg, bool smooth) {
  uint8_t servo = vertical[leg];
  //moveServo(servo, pulseLength(VERT_MAX), smooth);
  #ifdef DEBUG
    Serial.print("[INF]\t[PWM]\tLeg #");
    Serial.print(leg);
    Serial.print(" up ");
    if(smooth) {
      Serial.println("(smooth)");
    } else {
      Serial.println();
    }
  #endif
}

void AP_Utils::legDown(uint8_t leg, bool smooth) {
  uint8_t servo = vertical[leg];
  //moveServo(servo, pulseLength(VERT_MIN), smooth);
  #ifdef DEBUG
    Serial.print("[INF]\t[PWM]\tLeg #");
    Serial.print(leg);
    Serial.print(" down ");
    if(smooth) {
      Serial.println("(smooth)");
    } else {
      Serial.println();
    }
  #endif
}

void AP_Utils::moveServo(uint8_t number, int deg, bool smooth, float speed) {
  if(smooth) {
    float range = abs(servos[number].position - deg);
    if(servos[number].position > deg) {
      for(int i=servos[number].position; i>=deg; i--) {
        pwm.setPWM(servos[number].number, 0, pulseLength(i));
        float pause = (cos(((2.0*PI)/range)*(i-deg))+1.0)*speed;
        delayMicroseconds(pause*1000.0);
        #ifdef DEBUG
          Serial.println(pause);
        #endif
      }
    } else if(servos[number].position < deg) {
      for(int i=servos[number].position; i<=deg; i++) {
        pwm.setPWM(servos[number].number, 0, pulseLength(i));
        float pause = (cos(((2.0*PI)/range)*(i-servos[number].position))+1.0)*speed;
        delayMicroseconds(pause*1000.0);
        #ifdef DEBUG
          Serial.println(pause);
        #endif
      }
    }
    servos[number].position = deg;
  } else {
    pwmove(number, deg);
  }
  #ifdef DEBUG
    int bound = -1;
    if(servos[number].type == HORIZONTAL) {
      if(deg > HORIZ_MAX) {
        bound = HORIZ_MAX;
      } else if(deg < HORIZ_MIN) {
        bound = HORIZ_MIN;
      }
    } else if(servos[number].type == VERTICAL) {
      if(deg > VERT_MAX) {
        bound = VERT_MAX;
      } else if(deg < VERT_MIN) {
        bound = VERT_MIN;
      }
    }
    if(bound != -1) {
      Serial.print("[ERROR]\t[PWM]\tServo #");
      Serial.print(servos[number].number);
      Serial.println(" out of bounds!");

      Serial.print("\t\tCommand sent : ");
      Serial.print(deg);
      Serial.println(" deg");

      Serial.print("\t\tCurrent bound: ");
      Serial.print(bound);
      Serial.println(" deg");
    }
  #endif
}

void AP_Utils::legStretch(uint8_t leg, bool smooth) {
  legUp(leg, smooth);
  delay(50);
  legDown(leg, smooth);
  delay(50);
}

float AP_Utils::median(float *values, int numValues) {
  for(int i=0; i<(numValues-1); i++) {
    for(int j=0; j<(numValues-i-1); j++) {
      if(values[j+1] < values[j]) {
        float swap = values[j];
        values[j] = values[j+1];
        values[j+1] = swap;
      }
    }
  }

  /*for(int i=0; i<numValues; i++) {
    Serial.print(values[i]);
    Serial.print(' ');
  }
  Serial.print('\n');*/

  if(numValues%2 == 0) {
    return((values[numValues/2-1]+values[numValues/2])/2.0);
  }
  return(values[numValues/2]);
}<commit_msg>Delete AP_Utils.cpp<commit_after><|endoftext|>


<commit_before>#ifndef _SNARKFRONT_ALG_BOOL_HPP_
#define _SNARKFRONT_ALG_BOOL_HPP_

#include <cassert>
#include "Alg.hpp"

namespace snarkfront {

////////////////////////////////////////////////////////////////////////////////
// Alg_bool
//

template <typename FR>
void evalStackOp(std::stack<Alg_bool<FR>>& S, const LogicalOps op)
{
    typedef typename Alg_bool<FR>::R1T R1T;
    auto& RS = TL<R1C<FR>>::singleton();

    // y is right argument
    const auto R = S.top();
    S.pop();
    const bool yvalue = R.value();
#ifdef USE_ASSERT
    assert(1 == R.r1Terms().size());
#endif
    const R1T y = RS->argScalar(R);

    // z is result
    bool zvalue;
    FR zwitness;
    R1T z;

    // complement takes one argument
    if (LogicalOps::CMPLMNT == op) {
        zvalue = ! yvalue;
        zwitness = boolTo<FR>(zvalue);
        z = RS->createResult(op, y, y, zwitness);

    } else {
        // x is left argument
        const auto L = S.top();
        S.pop();
        const bool xvalue = L.value();
#ifdef USE_ASSERT
        assert(1 == L.r1Terms().size());
#endif
        const R1T x = RS->argScalar(L);

        zvalue = evalOp(op, xvalue, yvalue);
        zwitness = boolTo<FR>(zvalue);

        const bool
            xIsVar = x.isVariable(),
            yIsVar = y.isVariable();

        const LogicalOps NOT = LogicalOps::CMPLMNT;

        if (xIsVar == yIsVar) {
            z = RS->createResult(op, x, y, zwitness);

        } else if (xIsVar) { // && ! yIsVar
            if (yvalue) {
                switch (op) {
                case (LogicalOps::AND) : z = x; break;
                case (LogicalOps::OR) : z = y; break;
                case (LogicalOps::XOR) : z = RS->createResult(NOT, x, x, zwitness); break;
                case (LogicalOps::SAME) : z = x; break;
                }
            } else {
                switch (op) {
                case (LogicalOps::AND) : z = y; break;
                case (LogicalOps::OR) : z = x; break;
                case (LogicalOps::XOR) : z = x; break;
                case (LogicalOps::SAME) : z = RS->createResult(NOT, x, x, zwitness); break;
                }
            }

        } else if (yIsVar) { // && ! xIsVar
            if (xvalue) {
                switch (op) {
                case (LogicalOps::AND) : z = y; break;
                case (LogicalOps::OR) : z = x; break;
                case (LogicalOps::XOR) : z = RS->createResult(NOT, y, y, zwitness); break;
                case (LogicalOps::SAME) : z = y; break;
                }
            } else {
                switch (op) {
                case (LogicalOps::AND) : z = x; break;
                case (LogicalOps::OR) : z = y; break;
                case (LogicalOps::XOR) : z = y; break;
                case (LogicalOps::SAME) : z = RS->createResult(NOT, y, y, zwitness); break;
                }
            }
        }
    }

    S.push(
        Alg_bool<FR>(zvalue, zwitness, valueBits(zvalue), {z}));
}

template <typename FR>
void evalStackCmp(std::stack<Alg_bool<FR>>& S, const EqualityCmp op)
{
    typedef typename Alg_bool<FR>::R1T R1T;
    auto& RS = TL<R1C<FR>>::singleton();

    // y is right argument
    const auto R = S.top();
    S.pop();
    const bool yvalue = R.value();
    const R1T y = RS->argScalar(R);

    // x is left argument
    const auto L = S.top();
    S.pop();
    const bool xvalue = L.value();
    const R1T x = RS->argScalar(L);

    // z is result
    const bool zvalue = evalOp(op, xvalue, yvalue);
    const FR zwitness = boolTo<FR>(zvalue);
    const R1T z = RS->createResult(eqToLogical(op), x, y, zwitness);

    S.push(
        Alg_bool<FR>(zvalue, zwitness, valueBits(zvalue), {z}));
}

} // namespace snarkfront

#endif
<commit_msg>scope header file paths<commit_after>#ifndef _SNARKFRONT_ALG_BOOL_HPP_
#define _SNARKFRONT_ALG_BOOL_HPP_

#include <cassert>

#include <snarkfront/Alg.hpp>

namespace snarkfront {

////////////////////////////////////////////////////////////////////////////////
// Alg_bool
//

template <typename FR>
void evalStackOp(std::stack<Alg_bool<FR>>& S, const LogicalOps op)
{
    typedef typename Alg_bool<FR>::R1T R1T;
    auto& RS = TL<R1C<FR>>::singleton();

    // y is right argument
    const auto R = S.top();
    S.pop();
    const bool yvalue = R.value();
#ifdef USE_ASSERT
    assert(1 == R.r1Terms().size());
#endif
    const R1T y = RS->argScalar(R);

    // z is result
    bool zvalue;
    FR zwitness;
    R1T z;

    // complement takes one argument
    if (LogicalOps::CMPLMNT == op) {
        zvalue = ! yvalue;
        zwitness = boolTo<FR>(zvalue);
        z = RS->createResult(op, y, y, zwitness);

    } else {
        // x is left argument
        const auto L = S.top();
        S.pop();
        const bool xvalue = L.value();
#ifdef USE_ASSERT
        assert(1 == L.r1Terms().size());
#endif
        const R1T x = RS->argScalar(L);

        zvalue = evalOp(op, xvalue, yvalue);
        zwitness = boolTo<FR>(zvalue);

        const bool
            xIsVar = x.isVariable(),
            yIsVar = y.isVariable();

        const LogicalOps NOT = LogicalOps::CMPLMNT;

        if (xIsVar == yIsVar) {
            z = RS->createResult(op, x, y, zwitness);

        } else if (xIsVar) { // && ! yIsVar
            if (yvalue) {
                switch (op) {
                case (LogicalOps::AND) : z = x; break;
                case (LogicalOps::OR) : z = y; break;
                case (LogicalOps::XOR) : z = RS->createResult(NOT, x, x, zwitness); break;
                case (LogicalOps::SAME) : z = x; break;
                }
            } else {
                switch (op) {
                case (LogicalOps::AND) : z = y; break;
                case (LogicalOps::OR) : z = x; break;
                case (LogicalOps::XOR) : z = x; break;
                case (LogicalOps::SAME) : z = RS->createResult(NOT, x, x, zwitness); break;
                }
            }

        } else if (yIsVar) { // && ! xIsVar
            if (xvalue) {
                switch (op) {
                case (LogicalOps::AND) : z = y; break;
                case (LogicalOps::OR) : z = x; break;
                case (LogicalOps::XOR) : z = RS->createResult(NOT, y, y, zwitness); break;
                case (LogicalOps::SAME) : z = y; break;
                }
            } else {
                switch (op) {
                case (LogicalOps::AND) : z = x; break;
                case (LogicalOps::OR) : z = y; break;
                case (LogicalOps::XOR) : z = y; break;
                case (LogicalOps::SAME) : z = RS->createResult(NOT, y, y, zwitness); break;
                }
            }
        }
    }

    S.push(
        Alg_bool<FR>(zvalue, zwitness, valueBits(zvalue), {z}));
}

template <typename FR>
void evalStackCmp(std::stack<Alg_bool<FR>>& S, const EqualityCmp op)
{
    typedef typename Alg_bool<FR>::R1T R1T;
    auto& RS = TL<R1C<FR>>::singleton();

    // y is right argument
    const auto R = S.top();
    S.pop();
    const bool yvalue = R.value();
    const R1T y = RS->argScalar(R);

    // x is left argument
    const auto L = S.top();
    S.pop();
    const bool xvalue = L.value();
    const R1T x = RS->argScalar(L);

    // z is result
    const bool zvalue = evalOp(op, xvalue, yvalue);
    const FR zwitness = boolTo<FR>(zvalue);
    const R1T z = RS->createResult(eqToLogical(op), x, y, zwitness);

    S.push(
        Alg_bool<FR>(zvalue, zwitness, valueBits(zvalue), {z}));
}

} // namespace snarkfront

#endif
<|endoftext|>


<commit_before>// Ancillary.cc

#include "config.h"
#include "Ancillary.h"
#include "debug.h"

namespace libdap {

/** This function accepts a dataset path name, and searches for a
    matching ancillary data file name with a very specific set of
    search rules, given here:

    directory           filename          extension
    same                same            `.'given
    given               same            `.'given
    same                given           `.'given
    given               given           `.'given

    Where ``same'' refers to the input dataset pathname, and ``given''
    refers to the function arguments.

    For example, If you call this function with a
    dataset name of <tt>/a/data</tt>, an extension of <tt>das</tt>, a
    directory of
    <tt>b</tt>, and a filename of <tt>ralph</tt>, the function will
    look (in order)
    for the following files:

    /a/data.das
    /b/data.das
    /a/ralph.das
    /b/ralph.das

    The function will return a string containing the name of the first
    file in the list that exists, if any.

    @note This code now checks for pathname.ext 3/17/99 jhrg

    @brief Find a file with ancillary data.
    @param pathname The input pathname of a dataset.
    @param ext The input extension the desired file is to have.
    @param dir The input directory in which the desired file may be
    found.
    @param file The input filename the desired file may have.
    @return A string containing the pathname of the file found by
    searching with the given components.  If no file was found, the
    null string is returned.
*/
string
Ancillary::find_ancillary_file( const string &pathname,
				const string &ext,
				const string &dir,
				const string &file )
{
    string::size_type slash = pathname.rfind('/') + 1;
    string directory = pathname.substr(0, slash);
    string filename = pathname.substr(slash);
    string basename = pathname.substr(slash, pathname.rfind('.') - slash);

    DBG(cerr << "find ancillary file params: " << pathname << ", " << ext
        << ", " << dir << ", " << file << endl);
    DBG(cerr << "find ancillary file comp: " << directory << ", " << filename
        << ", " << basename << endl);

    string dot_ext = "." + ext;

    string name = directory + basename + dot_ext;
    if (access(name.c_str(), F_OK) == 0)
        return name;

    name = pathname + dot_ext;
    if (access(name.c_str(), F_OK) == 0)
        return name;

    name = directory + ext;
    if (access(name.c_str(), F_OK) == 0)
        return name;

    name = dir + basename + dot_ext;
    if (access(name.c_str(), F_OK) == 0)
        return name;

    name = directory + file + dot_ext;
    if (access(name.c_str(), F_OK) == 0)
        return name;

    name = dir + file + dot_ext;
    if (access(name.c_str(), F_OK) == 0)
        return name;

    name = dir + ext;
    if (access(name.c_str(), F_OK) == 0)
        return name;

    return "";
}

// Given a pathname to a datafile, take that pathname apart and look for an
// ancillary file that describes a group of datafiles of which this datafile
// is a member. Assume that groups follow a simple naming convention where
// files use either leading or trailing digits and a common basename to name
// group members. For example, 00stuff.hdf, 01stuff.hdf, 02stuff.hdf, ..., is
// a group and is has `stuff' as its basename.

/** Assume that <tt>name</tt> refers to a file that is one of a
    group of files which share a common `base' name and differ only by
    some prefix or suffix digits (e.g. <tt>00base</tt>, <tt>01base</tt>,
    ... or <tt>base00</tt>, ... have the base name <tt>base</tt>). This
    function looks for a file <tt>base.ext</tt>.

    @param name The name (full or relative) to one member of a group
    of files.
    @param ext The extension of the group's ancillary file. Note that
    <tt>ext</tt> should include a period (.) if that needs to
    separate the base name from the extension.
    @return The pathname to the group's ancillary file if found, otherwise
    the empty string (""). */
string
Ancillary::find_group_ancillary_file( const string &name, const string &ext )
{
    // Given /usr/local/data/stuff.01.nc
    // pathname = /usr/local/data, filename = stuff.01.nc and
    // rootname = stuff.01
    string::size_type slash = name.find_last_of('/');
    string dirname = name.substr(0, slash);
    string filename = name.substr(slash + 1);
    string rootname = filename.substr(0, filename.find_last_of('.'));

    // Instead of using regexs, scan the filename for leading and then
    // trailing digits.
    string::iterator rootname_iter = rootname.begin();
    string::iterator rootname_end_iter = rootname.end();
    if (isdigit(*rootname_iter)) {
        while (rootname_iter != rootname_end_iter
               && isdigit(*++rootname_iter))
            ;

        // We want: new_name = dirname + "/" + <base> + ext but without
        // creating a bunch of temp objects.
        string new_name = dirname;
        new_name.append("/");
        new_name.append(rootname_iter, rootname_end_iter);
        new_name.append(ext);
        DBG(cerr << "New Name (iter): " << new_name << endl);
        if (access(new_name.c_str(), F_OK) == 0) {
            return new_name;
        }
    }

    string::reverse_iterator rootname_riter = rootname.rbegin();
    string::reverse_iterator rootname_end_riter = rootname.rend();
    if (isdigit(*rootname_riter)) {
        while (rootname_riter != rootname_end_riter
               && isdigit(*++rootname_riter))
            ;
        string new_name = dirname;
        new_name.append("/");
        // I used reverse iters to scan rootname backwards. To avoid
        // reversing the fragment between end_riter and riter, pass append
        // regular iters obtained using reverse_iterator::base(). See Meyers
        // p. 123. 1/22/2002 jhrg
        new_name.append(rootname_end_riter.base(), rootname_riter.base());
        new_name.append(ext);
        DBG(cerr << "New Name (riter): " << new_name << endl);
        if (access(new_name.c_str(), F_OK) == 0) {
            return new_name;
        }
    }

    // If we're here either the file does not begin with leading digits or a
    // template made by removing those digits was not found.

    return "";
}

void
Ancillary::read_ancillary_das( DAS &das,
			       const string &pathname,
			       const string &dir,
			       const string &file )
{
    string name = find_ancillary_file( pathname, "das", dir, file ) ;

    FILE *in = fopen( name.c_str(), "r" ) ;
    if( in )
    {
        das.parse( in ) ;
        int res = fclose( in ) ;
        if( res )
	{
            DBG(cerr << "DODSFilter::read_ancillary_das - Failed to close file " << (void *)in << endl ;) ;
        }
    }
}

void
Ancillary::read_ancillary_dds( DDS &dds,
			       const string &pathname,
			       const string &dir,
			       const string &file )
{
    string name = find_ancillary_file( pathname, "dds", dir, file ) ;

    FILE *in = fopen( name.c_str(), "r" ) ;
    if( in )
    {
        dds.parse( in ) ;
        int res = fclose( in ) ;
        if( res )
	{
            DBG(cerr << "DODSFilter::read_ancillary_das - Failed to close file " << (void *)in << endl ;) ;
        }
    }
}

} // namespace libdap

<commit_msg>Added ifdef HAVE_UNISTD_H, include <unistd.h>, required on RedHat 3.+<commit_after>// Ancillary.cc

#include "config.h"
#include "Ancillary.h"
#include "debug.h"

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

namespace libdap {

/** This function accepts a dataset path name, and searches for a
    matching ancillary data file name with a very specific set of
    search rules, given here:

    directory           filename          extension
    same                same            `.'given
    given               same            `.'given
    same                given           `.'given
    given               given           `.'given

    Where ``same'' refers to the input dataset pathname, and ``given''
    refers to the function arguments.

    For example, If you call this function with a
    dataset name of <tt>/a/data</tt>, an extension of <tt>das</tt>, a
    directory of
    <tt>b</tt>, and a filename of <tt>ralph</tt>, the function will
    look (in order)
    for the following files:

    /a/data.das
    /b/data.das
    /a/ralph.das
    /b/ralph.das

    The function will return a string containing the name of the first
    file in the list that exists, if any.

    @note This code now checks for pathname.ext 3/17/99 jhrg

    @brief Find a file with ancillary data.
    @param pathname The input pathname of a dataset.
    @param ext The input extension the desired file is to have.
    @param dir The input directory in which the desired file may be
    found.
    @param file The input filename the desired file may have.
    @return A string containing the pathname of the file found by
    searching with the given components.  If no file was found, the
    null string is returned.
*/
string
Ancillary::find_ancillary_file( const string &pathname,
				const string &ext,
				const string &dir,
				const string &file )
{
    string::size_type slash = pathname.rfind('/') + 1;
    string directory = pathname.substr(0, slash);
    string filename = pathname.substr(slash);
    string basename = pathname.substr(slash, pathname.rfind('.') - slash);

    DBG(cerr << "find ancillary file params: " << pathname << ", " << ext
        << ", " << dir << ", " << file << endl);
    DBG(cerr << "find ancillary file comp: " << directory << ", " << filename
        << ", " << basename << endl);

    string dot_ext = "." + ext;

    string name = directory + basename + dot_ext;
    if (access(name.c_str(), F_OK) == 0)
        return name;

    name = pathname + dot_ext;
    if (access(name.c_str(), F_OK) == 0)
        return name;

    name = directory + ext;
    if (access(name.c_str(), F_OK) == 0)
        return name;

    name = dir + basename + dot_ext;
    if (access(name.c_str(), F_OK) == 0)
        return name;

    name = directory + file + dot_ext;
    if (access(name.c_str(), F_OK) == 0)
        return name;

    name = dir + file + dot_ext;
    if (access(name.c_str(), F_OK) == 0)
        return name;

    name = dir + ext;
    if (access(name.c_str(), F_OK) == 0)
        return name;

    return "";
}

// Given a pathname to a datafile, take that pathname apart and look for an
// ancillary file that describes a group of datafiles of which this datafile
// is a member. Assume that groups follow a simple naming convention where
// files use either leading or trailing digits and a common basename to name
// group members. For example, 00stuff.hdf, 01stuff.hdf, 02stuff.hdf, ..., is
// a group and is has `stuff' as its basename.

/** Assume that <tt>name</tt> refers to a file that is one of a
    group of files which share a common `base' name and differ only by
    some prefix or suffix digits (e.g. <tt>00base</tt>, <tt>01base</tt>,
    ... or <tt>base00</tt>, ... have the base name <tt>base</tt>). This
    function looks for a file <tt>base.ext</tt>.

    @param name The name (full or relative) to one member of a group
    of files.
    @param ext The extension of the group's ancillary file. Note that
    <tt>ext</tt> should include a period (.) if that needs to
    separate the base name from the extension.
    @return The pathname to the group's ancillary file if found, otherwise
    the empty string (""). */
string
Ancillary::find_group_ancillary_file( const string &name, const string &ext )
{
    // Given /usr/local/data/stuff.01.nc
    // pathname = /usr/local/data, filename = stuff.01.nc and
    // rootname = stuff.01
    string::size_type slash = name.find_last_of('/');
    string dirname = name.substr(0, slash);
    string filename = name.substr(slash + 1);
    string rootname = filename.substr(0, filename.find_last_of('.'));

    // Instead of using regexs, scan the filename for leading and then
    // trailing digits.
    string::iterator rootname_iter = rootname.begin();
    string::iterator rootname_end_iter = rootname.end();
    if (isdigit(*rootname_iter)) {
        while (rootname_iter != rootname_end_iter
               && isdigit(*++rootname_iter))
            ;

        // We want: new_name = dirname + "/" + <base> + ext but without
        // creating a bunch of temp objects.
        string new_name = dirname;
        new_name.append("/");
        new_name.append(rootname_iter, rootname_end_iter);
        new_name.append(ext);
        DBG(cerr << "New Name (iter): " << new_name << endl);
        if (access(new_name.c_str(), F_OK) == 0) {
            return new_name;
        }
    }

    string::reverse_iterator rootname_riter = rootname.rbegin();
    string::reverse_iterator rootname_end_riter = rootname.rend();
    if (isdigit(*rootname_riter)) {
        while (rootname_riter != rootname_end_riter
               && isdigit(*++rootname_riter))
            ;
        string new_name = dirname;
        new_name.append("/");
        // I used reverse iters to scan rootname backwards. To avoid
        // reversing the fragment between end_riter and riter, pass append
        // regular iters obtained using reverse_iterator::base(). See Meyers
        // p. 123. 1/22/2002 jhrg
        new_name.append(rootname_end_riter.base(), rootname_riter.base());
        new_name.append(ext);
        DBG(cerr << "New Name (riter): " << new_name << endl);
        if (access(new_name.c_str(), F_OK) == 0) {
            return new_name;
        }
    }

    // If we're here either the file does not begin with leading digits or a
    // template made by removing those digits was not found.

    return "";
}

void
Ancillary::read_ancillary_das( DAS &das,
			       const string &pathname,
			       const string &dir,
			       const string &file )
{
    string name = find_ancillary_file( pathname, "das", dir, file ) ;

    FILE *in = fopen( name.c_str(), "r" ) ;
    if( in )
    {
        das.parse( in ) ;
        int res = fclose( in ) ;
        if( res )
	{
            DBG(cerr << "DODSFilter::read_ancillary_das - Failed to close file " << (void *)in << endl ;) ;
        }
    }
}

void
Ancillary::read_ancillary_dds( DDS &dds,
			       const string &pathname,
			       const string &dir,
			       const string &file )
{
    string name = find_ancillary_file( pathname, "dds", dir, file ) ;

    FILE *in = fopen( name.c_str(), "r" ) ;
    if( in )
    {
        dds.parse( in ) ;
        int res = fclose( in ) ;
        if( res )
	{
            DBG(cerr << "DODSFilter::read_ancillary_das - Failed to close file " << (void *)in << endl ;) ;
        }
    }
}

} // namespace libdap

<|endoftext|>


<commit_before>/**
   m30c10 keyboard firmware for TeensyLC
   https://github.com/hoosierEE/m30c10
*/
#include <Arduino.h>
const uint32_t MS_OUT{10}; elapsedMillis t; // min. output period

//// Model
static const uint8_t COLS{5}; // 2 columns for index finger, 1 each for middle/ring/pinkie
static const uint8_t ROWS{6}; // 3 rows per hand
const int TEENSY_ROW_PIN[ROWS]{10,11,12,14,20,21};
const int TEENSY_COL_PIN[COLS]{2,5,6,7,8}; // pin 9 is also available if more switches req'd
struct Grid { bool keys[COLS][ROWS]; } raw_grid;

//// Key Layers
char *default_layer[]{"qwert","yuiop","asdfg","hjkl'","zxcvb","nm,.-"};
char *shifted_layer[]{"QWERT","YUIOP","ASDFG","HJKL\"","ZXCVB","NM?!:"};
char *numeric_layer[]{"75319","02468","12345","67890","():,%",".+-*/"};
char *symbol_layer []{"@#$%[","]^&*|"," -+=(",");:/\\","_~`!{","}<,.>"};

//// Functions
void set_pins(void)
{
    for (int i=0;i<COLS;++i) {
        pinMode(TEENSY_COL_PIN[i], OUTPUT);
        for (int j=0;j<ROWS;++j) {
            pinMode(TEENSY_ROW_PIN[j], INPUT_PULLUP);
        }
    }
}

Grid scan(void)
{
    Grid g;
    for (int i=0;i<COLS;++i) {
        digitalWrite(TEENSY_COL_PIN[i],LOW); // pull column low
        for (int j=0;j<ROWS;++j) {
            g.keys[i][j] = digitalRead(TEENSY_ROW_PIN[i]); // populate grid
        }
        digitalWrite(TEENSY_COL_PIN[i],HIGH); // restore column
    }
    return g;
}

void print_grid(Grid g)
{
    // for debugging
    for (int i=0;i<COLS;++i) {
        for (int j=0;j<ROWS;++j) {
            if (g.keys[i][j]) { Serial.print(default_layer[i][j]); }
        }
    }
    Serial.println("");
}

void setup() {
    set_pins();
}
void loop() {
    print_grid(scan()); // read inputs

    if (t >= MS_OUT) {
        t -= MS_OUT;
        // TODO: output if changed
    }
}
<commit_msg>whitespace<commit_after>/**
   m30c10 keyboard firmware for TeensyLC
   https://github.com/hoosierEE/m30c10
*/
// #include <Arduino.h>
const uint32_t MS_OUT{10}; elapsedMillis t; // min. output period

//// Model
static const uint8_t COLS{5}; // 2 columns for index finger, 1 each for middle/ring/pinkie
static const uint8_t ROWS{6}; // 3 rows per hand
const int TEENSY_ROW_PIN[ROWS]{10,11,12,14,20,21};
const int TEENSY_COL_PIN[COLS]{2,5,6,7,8}; // pin 9 is also available if more switches req'd
struct Grid { bool keys[COLS][ROWS]; } raw_grid;

//// Key Layers
char *default_layer[]{"qwert","yuiop","asdfg","hjkl'","zxcvb","nm,.-"};
char *shifted_layer[]{"QWERT","YUIOP","ASDFG","HJKL\"","ZXCVB","NM?!:"};
char *numeric_layer[]{"75319","02468","12345","67890","():,%",".+-*/"};
char *symbol_layer []{"@#$%[","]^&*|"," -+=(",");:/\\","_~`!{","}<,.>"};

//// Functions
void set_pins(void)
{
    for (int i=0;i<COLS;++i) {
        pinMode(TEENSY_COL_PIN[i], OUTPUT);
        for (int j=0;j<ROWS;++j) {
            pinMode(TEENSY_ROW_PIN[j], INPUT_PULLUP);
        }
    }
}

Grid scan(void)
{
    Grid g;
    for (int i=0;i<COLS;++i) {
        digitalWrite(TEENSY_COL_PIN[i],LOW); // pull column low
        for (int j=0;j<ROWS;++j) {
            g.keys[i][j] = digitalRead(TEENSY_ROW_PIN[i]); // populate grid
        }
        digitalWrite(TEENSY_COL_PIN[i],HIGH); // restore column
    }
    return g;
}

void print_grid(Grid g)
{
    // for debugging
    for (int i=0// ;
         i<COLS;++i) {
        for (int j=0;j<ROWS;++j) {
            if (g.keys[i][j]) { Serial.print(default_layer[i][j]); }
        }
    }
    Serial.println("");
}

void setup() {
    set_pins();
}
void loop() {
    print_grid(scan()); // read inputs

    if(t>=MS_OUT){
        t-=MS_OUT;
        // TODO: output if changed
    }
}
<|endoftext|>


<commit_before>/* Test for throwing an exception from the copy ctor of the exception object
 * invoked while building an exception.
 */
#include <stdio.h>

struct foo {
  foo() {}
  foo(const foo &F) { throw 1; }
};

int main() {
	try {
		foo f;
		throw f;
	} catch (int i) {
		printf("Success!\n");
		return 0;
	} catch (foo &f) {
		printf("Failure: caught a foo!\n");
		return 1;
	} catch (...) {
		printf("Failure: caught something else!\n");
		return 1;
	}
}
<commit_msg>Move the testcase elsewhere<commit_after><|endoftext|>


<commit_before>#pragma once
#include "duke/base/Slice.hpp"
#include <algorithm>
#include <limits>
#include <utility>

#include <cstdlib>
#include <cstdint>
#include <cstring>

#define MAY_ALIAS __attribute__((__may_alias__))
/**
 * A buffer with small size optimization.
 *
 * If size is less or equal to SMALL_SIZE no allocation is performed.
 * Otherwise malloc/free is called to dynamically allocate the memory.
 * The structure is designed to be minimal yet efficient by enabling move
 * construction and assignment.
 */
template <size_t SMALL_SIZE_>
struct SmallBuffer {
  static constexpr size_t SMALL_SIZE = SMALL_SIZE_;
  static_assert(SMALL_SIZE >= sizeof(void *), "SmallData should at least be of pointer size, T>=8");

  SmallBuffer() : _size(0) { allocate(); }

  SmallBuffer(size_t size) : _size(size) { allocate(); }

  SmallBuffer(const void *ptr, size_t size) : _size(size) { allocateAndCopy(ptr); }

  SmallBuffer(MemorySlice slice) : SmallBuffer(slice.begin(), slice.size()) {}

  SmallBuffer(const SmallBuffer &other) : _size(other._size) { allocateAndCopy(other.begin()); }

  SmallBuffer &operator=(const SmallBuffer &other) {
    if (_size != other._size) {
      release();
      _size = other._size;
    }
    allocateAndCopy(other.begin());
    return *this;
  }

  SmallBuffer(SmallBuffer &&other) : _size(0) { stealContentFrom(std::move(other)); }

  SmallBuffer &operator=(SmallBuffer &&other) {
    release();
    stealContentFrom(std::move(other));
    return *this;
  }

  ~SmallBuffer() { release(); }

  inline const uint8_t *begin() const { return addressof(); }
  inline uint8_t *begin() { return addressof(); }

  inline const uint8_t *end() const { return begin() + _size; }
  inline uint8_t *end() { return begin() + _size; }

  void fill(const void *ptr) { memcpy(addressof(), ptr, _size); }

  inline size_t size() const { return _size; }

  inline bool empty() const { return _size == 0; }

  bool operator==(const SmallBuffer &other) const {
    return size() == other.size() && std::equal(begin(), end(), other.begin());
  }

 private:
  template <typename T>
  T &as(void *ptr) {
    return *reinterpret_cast<T *>(ptr);
  }
  template <typename T>
  T as(const void *ptr) const {
    return *reinterpret_cast<const T *>(ptr);
  }

  inline void setDynamicPtr(void *ptr) { as<void *>(_storage) = ptr; }

  inline uint8_t *addressof() { return isAllocated() ? as<uint8_t *>(_storage) : _storage; }

  inline const uint8_t *addressof() const { return isAllocated() ? as<const uint8_t *>(_storage) : _storage; }

  inline bool isAllocated() const { return _size > SMALL_SIZE; }

  inline void allocate() {
    if (isAllocated()) setDynamicPtr(malloc(_size));
  }

  inline void release() {
    if (isAllocated()) free(addressof());
    _size = 0;
  }

  void allocateAndCopy(const void *ptr) {
    allocate();
    fill(ptr);
  }

  void stealContentFrom(SmallBuffer &&other) {
    memcpy(_storage, other._storage, sizeof(_storage));
    _size = other._size;
    other._size = 0;
  }

  size_t _size;
  uint8_t _storage[SMALL_SIZE];
};
<commit_msg>remove unused define<commit_after>#pragma once
#include "duke/base/Slice.hpp"
#include <algorithm>
#include <limits>
#include <utility>

#include <cstdlib>
#include <cstdint>
#include <cstring>

/**
 * A buffer with small size optimization.
 *
 * If size is less or equal to SMALL_SIZE no allocation is performed.
 * Otherwise malloc/free is called to dynamically allocate the memory.
 * The structure is designed to be minimal yet efficient by enabling move
 * construction and assignment.
 */
template <size_t SMALL_SIZE_>
struct SmallBuffer {
  static constexpr size_t SMALL_SIZE = SMALL_SIZE_;
  static_assert(SMALL_SIZE >= sizeof(void *), "SmallData should at least be of pointer size, T>=8");

  SmallBuffer() : _size(0) { allocate(); }

  SmallBuffer(size_t size) : _size(size) { allocate(); }

  SmallBuffer(const void *ptr, size_t size) : _size(size) { allocateAndCopy(ptr); }

  SmallBuffer(MemorySlice slice) : SmallBuffer(slice.begin(), slice.size()) {}

  SmallBuffer(const SmallBuffer &other) : _size(other._size) { allocateAndCopy(other.begin()); }

  SmallBuffer &operator=(const SmallBuffer &other) {
    if (_size != other._size) {
      release();
      _size = other._size;
    }
    allocateAndCopy(other.begin());
    return *this;
  }

  SmallBuffer(SmallBuffer &&other) : _size(0) { stealContentFrom(std::move(other)); }

  SmallBuffer &operator=(SmallBuffer &&other) {
    release();
    stealContentFrom(std::move(other));
    return *this;
  }

  ~SmallBuffer() { release(); }

  inline const uint8_t *begin() const { return addressof(); }
  inline uint8_t *begin() { return addressof(); }

  inline const uint8_t *end() const { return begin() + _size; }
  inline uint8_t *end() { return begin() + _size; }

  void fill(const void *ptr) { memcpy(addressof(), ptr, _size); }

  inline size_t size() const { return _size; }

  inline bool empty() const { return _size == 0; }

  bool operator==(const SmallBuffer &other) const {
    return size() == other.size() && std::equal(begin(), end(), other.begin());
  }

 private:
  template <typename T>
  T &as(void *ptr) {
    return *reinterpret_cast<T *>(ptr);
  }
  template <typename T>
  T as(const void *ptr) const {
    return *reinterpret_cast<const T *>(ptr);
  }

  inline void setDynamicPtr(void *ptr) { as<void *>(_storage) = ptr; }

  inline uint8_t *addressof() { return isAllocated() ? as<uint8_t *>(_storage) : _storage; }

  inline const uint8_t *addressof() const { return isAllocated() ? as<const uint8_t *>(_storage) : _storage; }

  inline bool isAllocated() const { return _size > SMALL_SIZE; }

  inline void allocate() {
    if (isAllocated()) setDynamicPtr(malloc(_size));
  }

  inline void release() {
    if (isAllocated()) free(addressof());
    _size = 0;
  }

  void allocateAndCopy(const void *ptr) {
    allocate();
    fill(ptr);
  }

  void stealContentFrom(SmallBuffer &&other) {
    memcpy(_storage, other._storage, sizeof(_storage));
    _size = other._size;
    other._size = 0;
  }

  size_t _size;
  uint8_t _storage[SMALL_SIZE];
};
<|endoftext|>


<commit_before>// Test that instrumentation based profiling feeds branch prediction
// correctly. This tests both generation of profile data and use of the same,
// and the input file for the -fprofile-instr-use case is expected to be result
// of running the program generated by the -fprofile-instr-generate case
// (excepting no_usable_data). As such, main() should call every function in
// this test.

// RUN: %clang %s -o - -emit-llvm -S -fprofile-instr-generate -fno-exceptions -target %itanium_abi_triple > %tgen
// RUN: FileCheck --input-file=%tgen -check-prefix=CTRGEN %s
// RUN: FileCheck --input-file=%tgen -check-prefix=DTRGEN %s
// RUN: FileCheck --input-file=%tgen -check-prefix=MTHGEN %s
// RUN: FileCheck --input-file=%tgen -check-prefix=WRPGEN %s

// RUN: %clang %s -o - -emit-llvm -S -fprofile-instr-use=%S/Inputs/instr-profile-class.pgodata -fno-exceptions -target %itanium_abi_triple > %tuse
// RUN: FileCheck --input-file=%tuse -check-prefix=CTRUSE %s
// RUN: FileCheck --input-file=%tuse -check-prefix=DTRUSE %s
// RUN: FileCheck --input-file=%tuse -check-prefix=MTHUSE %s
// RUN: FileCheck --input-file=%tuse -check-prefix=WRPUSE %s

class Simple {
  int Member;
public:
  // CTRGEN-LABEL: define {{.*}} @_ZN6SimpleC2Ei(
  // CTRUSE-LABEL: define {{.*}} @_ZN6SimpleC2Ei(
  // CTRGEN: store {{.*}} @[[SCC:__llvm_pgo_ctr[0-9]*]], i64 0, i64 0
  explicit Simple(int Member) : Member(Member) {
    // CTRGEN: store {{.*}} @[[SCC]], i64 0, i64 1
    // CTRUSE: br {{.*}} !prof ![[SC1:[0-9]+]]
    if (Member) {}
    // CTRGEN-NOT: store {{.*}} @[[SCC]],
    // CTRUSE-NOT: br {{.*}} !prof ![0-9]+
    // CTRUSE: ret void
  }
  // CTRUSE: ![[SC1]] = metadata !{metadata !"branch_weights", i32 100, i32 2}

  // DTRGEN-LABEL: define {{.*}} @_ZN6SimpleD2Ev(
  // DTRUSE-LABEL: define {{.*}} @_ZN6SimpleD2Ev(
  // DTRGEN: store {{.*}} @[[SDC:__llvm_pgo_ctr[0-9]*]], i64 0, i64 0
  ~Simple() {
    // DTRGEN: store {{.*}} @[[SDC]], i64 0, i64 1
    // DTRUSE: br {{.*}} !prof ![[SD1:[0-9]+]]
    if (Member) {}
    // DTRGEN-NOT: store {{.*}} @[[SDC]],
    // DTRUSE-NOT: br {{.*}} !prof ![0-9]+
    // DTRUSE: ret void
  }
  // DTRUSE: ![[SD1]] = metadata !{metadata !"branch_weights", i32 100, i32 2}

  // MTHGEN-LABEL: define {{.*}} @_ZN6Simple6methodEv(
  // MTHUSE-LABEL: define {{.*}} @_ZN6Simple6methodEv(
  // MTHGEN: store {{.*}} @[[SMC:__llvm_pgo_ctr[0-9]*]], i64 0, i64 0
  void method() {
    // MTHGEN: store {{.*}} @[[SMC]], i64 0, i64 1
    // MTHUSE: br {{.*}} !prof ![[SM1:[0-9]+]]
    if (Member) {}
    // MTHGEN-NOT: store {{.*}} @[[SMC]],
    // MTHUSE-NOT: br {{.*}} !prof ![0-9]+
    // MTHUSE: ret void
  }
  // MTHUSE: ![[SM1]] = metadata !{metadata !"branch_weights", i32 100, i32 2}
};

// WRPGEN-LABEL: define {{.*}} @_Z14simple_wrapperv(
// WRPUSE-LABEL: define {{.*}} @_Z14simple_wrapperv(
// WRPGEN: store {{.*}} @[[SWC:__llvm_pgo_ctr[0-9]*]], i64 0, i64 0
void simple_wrapper() {
  // WRPGEN: store {{.*}} @[[SWC]], i64 0, i64 1
  // WRPUSE: br {{.*}} !prof ![[SW1:[0-9]+]]
  for (int I = 0; I < 100; ++I) {
    Simple S(I);
    S.method();
  }
  // WRPGEN-NOT: store {{.*}} @[[SWC]],
  // WRPUSE-NOT: br {{.*}} !prof ![0-9]+
  // WRPUSE: ret void
}
// WRPUSE: ![[SW1]] = metadata !{metadata !"branch_weights", i32 100, i32 2}

int main(int argc, const char *argv[]) {
  simple_wrapper();
  return 0;
}
<commit_msg>test/CodeGenCXX: Be less strict about return types<commit_after>// Test that instrumentation based profiling feeds branch prediction
// correctly. This tests both generation of profile data and use of the same,
// and the input file for the -fprofile-instr-use case is expected to be result
// of running the program generated by the -fprofile-instr-generate case
// (excepting no_usable_data). As such, main() should call every function in
// this test.

// RUN: %clang %s -o - -emit-llvm -S -fprofile-instr-generate -fno-exceptions -target %itanium_abi_triple > %tgen
// RUN: FileCheck --input-file=%tgen -check-prefix=CTRGEN %s
// RUN: FileCheck --input-file=%tgen -check-prefix=DTRGEN %s
// RUN: FileCheck --input-file=%tgen -check-prefix=MTHGEN %s
// RUN: FileCheck --input-file=%tgen -check-prefix=WRPGEN %s

// RUN: %clang %s -o - -emit-llvm -S -fprofile-instr-use=%S/Inputs/instr-profile-class.pgodata -fno-exceptions -target %itanium_abi_triple > %tuse
// RUN: FileCheck --input-file=%tuse -check-prefix=CTRUSE %s
// RUN: FileCheck --input-file=%tuse -check-prefix=DTRUSE %s
// RUN: FileCheck --input-file=%tuse -check-prefix=MTHUSE %s
// RUN: FileCheck --input-file=%tuse -check-prefix=WRPUSE %s

class Simple {
  int Member;
public:
  // CTRGEN-LABEL: define {{.*}} @_ZN6SimpleC2Ei(
  // CTRUSE-LABEL: define {{.*}} @_ZN6SimpleC2Ei(
  // CTRGEN: store {{.*}} @[[SCC:__llvm_pgo_ctr[0-9]*]], i64 0, i64 0
  explicit Simple(int Member) : Member(Member) {
    // CTRGEN: store {{.*}} @[[SCC]], i64 0, i64 1
    // CTRUSE: br {{.*}} !prof ![[SC1:[0-9]+]]
    if (Member) {}
    // CTRGEN-NOT: store {{.*}} @[[SCC]],
    // CTRUSE-NOT: br {{.*}} !prof ![0-9]+
    // CTRUSE: ret
  }
  // CTRUSE: ![[SC1]] = metadata !{metadata !"branch_weights", i32 100, i32 2}

  // DTRGEN-LABEL: define {{.*}} @_ZN6SimpleD2Ev(
  // DTRUSE-LABEL: define {{.*}} @_ZN6SimpleD2Ev(
  // DTRGEN: store {{.*}} @[[SDC:__llvm_pgo_ctr[0-9]*]], i64 0, i64 0
  ~Simple() {
    // DTRGEN: store {{.*}} @[[SDC]], i64 0, i64 1
    // DTRUSE: br {{.*}} !prof ![[SD1:[0-9]+]]
    if (Member) {}
    // DTRGEN-NOT: store {{.*}} @[[SDC]],
    // DTRUSE-NOT: br {{.*}} !prof ![0-9]+
    // DTRUSE: ret
  }
  // DTRUSE: ![[SD1]] = metadata !{metadata !"branch_weights", i32 100, i32 2}

  // MTHGEN-LABEL: define {{.*}} @_ZN6Simple6methodEv(
  // MTHUSE-LABEL: define {{.*}} @_ZN6Simple6methodEv(
  // MTHGEN: store {{.*}} @[[SMC:__llvm_pgo_ctr[0-9]*]], i64 0, i64 0
  void method() {
    // MTHGEN: store {{.*}} @[[SMC]], i64 0, i64 1
    // MTHUSE: br {{.*}} !prof ![[SM1:[0-9]+]]
    if (Member) {}
    // MTHGEN-NOT: store {{.*}} @[[SMC]],
    // MTHUSE-NOT: br {{.*}} !prof ![0-9]+
    // MTHUSE: ret
  }
  // MTHUSE: ![[SM1]] = metadata !{metadata !"branch_weights", i32 100, i32 2}
};

// WRPGEN-LABEL: define {{.*}} @_Z14simple_wrapperv(
// WRPUSE-LABEL: define {{.*}} @_Z14simple_wrapperv(
// WRPGEN: store {{.*}} @[[SWC:__llvm_pgo_ctr[0-9]*]], i64 0, i64 0
void simple_wrapper() {
  // WRPGEN: store {{.*}} @[[SWC]], i64 0, i64 1
  // WRPUSE: br {{.*}} !prof ![[SW1:[0-9]+]]
  for (int I = 0; I < 100; ++I) {
    Simple S(I);
    S.method();
  }
  // WRPGEN-NOT: store {{.*}} @[[SWC]],
  // WRPUSE-NOT: br {{.*}} !prof ![0-9]+
  // WRPUSE: ret
}
// WRPUSE: ![[SW1]] = metadata !{metadata !"branch_weights", i32 100, i32 2}

int main(int argc, const char *argv[]) {
  simple_wrapper();
  return 0;
}
<|endoftext|>


<commit_before>// Based on Herb Sutter's talk at C++ and beyond 2012
// He made T t; mutable which I think is incorrect

#include <iostream>
#include <algorithm>
#include <string>
#include <thread>
#include <vector>

template <typename T>
class Monitor
{
	T t;
	mutable std::mutex m;
public:
	Monitor(T _t) : t(_t) {}

	template <typename F>
	auto operator()(F f) -> decltype(f(t))
	{
		std::lock_guard<std::mutex> l(m);
		return f(t);
	}
};

int main(int argc, char* argv[])
{
	Monitor<std::ostream&> async_ios(std::ref(std::cout));

	std::vector<std::thread> threads;

	threads.emplace_back([&](){
			async_ios(
				[](std::ostream& io){ io << "Hello 1" << std::endl;});
			});
	threads.emplace_back([&](){
			async_ios(
				[](std::ostream& io){ io << "Hello 2" << std::endl;});
			});
	threads.emplace_back([&](){
			async_ios(
				[](std::ostream& io){ io << "Hello 3" << std::endl;});
			});
	threads.emplace_back([&](){
			async_ios(
				[](std::ostream& io){ io << "Hello 4" << std::endl;});
			});

	for(auto& t : threads) { t.join(); }
}

<commit_msg>Update Monitor/Monitor.cpp<commit_after>// Based on Herb Sutter's talk at C++ and beyond 2012
// He made T t; mutable which I think is incorrect

#include <iostream>
#include <algorithm>
#include <string>
#include <thread>
#include <vector>

template <typename T>
class Monitor
{
	T t;
	std::mutex m;
public:
	Monitor(T _t) : t(_t) {}

	template <typename F>
	auto operator()(F f) -> decltype(f(t))
	{
		std::lock_guard<std::mutex> l(m);
		return f(t);
	}
};

int main(int argc, char* argv[])
{
	Monitor<std::ostream&> async_ios(std::ref(std::cout));

	std::vector<std::thread> threads;

	threads.emplace_back([&](){
			async_ios(
				[](std::ostream& io){ io << "Hello 1" << std::endl;});
			});
	threads.emplace_back([&](){
			async_ios(
				[](std::ostream& io){ io << "Hello 2" << std::endl;});
			});
	threads.emplace_back([&](){
			async_ios(
				[](std::ostream& io){ io << "Hello 3" << std::endl;});
			});
	threads.emplace_back([&](){
			async_ios(
				[](std::ostream& io){ io << "Hello 4" << std::endl;});
			});

	for(auto& t : threads) { t.join(); }
}

<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
#include <malloc.h>
#ifdef _MSC_VER
#include <cstdlib>
#define alignedMalloc(size,align)	_aligned_malloc(size,align)
#define alignedFree(ptr)			_aligned_free(ptr)
#elif defined (__GNUC__)
#define alignedMalloc(size,align)	memalign(align,size)
#define alignedFree(ptr)			free(ptr)
#endif
#include "floatMul.h"
#include "featureSupport.h"
#include "simdUtils.h"

const int ALIGN   = 16; // alignment step for SSE
const int cWidth  = 256;
const int cHeight = cWidth;
const int cSize   = cHeight * cWidth;

half4 compressToHalf4(uint4 integer, float4 srcVector)
{
	float4 dstFloat4;
	dstFloat4 = convert_uint4_float4(integer);
	dstFloat4 = multiply_float4(dstFloat4, srcVector);
	return convert_float4_half4(dstFloat4);
}

uint4 uncompressToInt4(half4 halfVector, float4 srcVector)
{
	float4 dstFloat4;
	dstFloat4 = convert_half4_float4(halfVector);
	dstFloat4 = multiply_float4(dstFloat4, srcVector);
	return convert_float4_uint4(dstFloat4);
}

bool verifyMultiply()
{
	float _originalFloat[] = {1.1f,  1.49f, 1.50f, 1.99f, 1.0000001f, 1.4999999f, 1.5000000f, 1.9999999f, };
	float* originalFloat = reinterpret_cast<float*>(alignedMalloc(8*sizeof(float),ALIGN));
	unsigned int* converted = reinterpret_cast<unsigned int*>(alignedMalloc(8*sizeof(float),ALIGN));
	for (int i = 0;i < 8;i++)
	{
		originalFloat[i] = _originalFloat[i];
	}

	float4 srcFloat1 = load_float4((const float*)originalFloat);
	float4 srcFloat2 = load_float4((const float*)&originalFloat[4]);
	uint4 dstInt1 = convert_float4_uint4(srcFloat1);
	uint4 dstInt2 = convert_float4_uint4(srcFloat2);
	store_uint4(&converted[0], dstInt1);
	store_uint4(&converted[4], dstInt2);

	std::cout << originalFloat[0] << '\t' << originalFloat[1] << '\t' << originalFloat[2] << '\t' << originalFloat[3] << std::endl;
	std::cout << converted[0]     << '\t' << converted[1]     << '\t' << converted[2]     << '\t' << converted[3]     << std::endl;
	std::cout << originalFloat[4] << '\t' << originalFloat[5] << '\t' << originalFloat[6] << '\t' << originalFloat[7] << std::endl;
	std::cout << converted[4]     << '\t' << converted[5]     << '\t' << converted[6]     << '\t' << converted[7]     << std::endl;

	const unsigned char cParallel = 8;
	unsigned char _original[] = {0, 1, 2, 3, 4, 5, 6, 7, };
	uchar8 step     = load_uchar8_repeat(cParallel);
	uchar8 original = load_uchar8(_original);
	char before[cParallel], after[cParallel];
	float* _srcVectorDiv = reinterpret_cast<float*>(alignedMalloc(4*sizeof(float),ALIGN));
	float* _srcVectorMul = reinterpret_cast<float*>(alignedMalloc(4*sizeof(float),ALIGN));
	bool passedFlag = true;
	for (int src = 1;src < 256;src++)
	{
		for (int i = 0;i < 4;i++)
		{
			_srcVectorDiv[i] = 1.0f/(float)src;
			_srcVectorMul[i] = (float)src;
		}
		float4 srcVectorDiv = load_float4(_srcVectorDiv);
		float4 srcVectorMul = load_float4(_srcVectorMul);
		uchar8 dst = original;
		for (int i = 0;i <= 256 - cParallel;i += cParallel)
		{
			// compress the gain
			ushort8 dstShort8     = convert_uchar8_ushort8(dst);
			uint4 dstIntegerLow4  = convert_ushort8_lo_uint4(dstShort8);
			uint4 dstIntegerHigh4 = convert_ushort8_hi_uint4(dstShort8);
			half4 compressLow4    = compressToHalf4(dstIntegerLow4,  srcVectorDiv);
			half4 compressHigh4   = compressToHalf4(dstIntegerHigh4, srcVectorDiv);

			// uncompress the gain
			dstIntegerLow4  = uncompressToInt4(compressLow4,  srcVectorMul);
			dstIntegerHigh4 = uncompressToInt4(compressHigh4, srcVectorMul);
			dstShort8       = convert_uint4_ushort8(dstIntegerLow4, dstIntegerHigh4);
			uchar8 resultChar8;
			resultChar8     = convert_ushort8_uchar8(dstShort8);

			store_uchar8((void*)before, dst);
			store_uchar8((void*)after,  resultChar8);
			dst = dst + step;
			for (int j = 0;j < cParallel;j++)
			{
				if (before[j] != after[j])
				{
					std::cerr << "error: src:" << src << " expected:" << (unsigned int)before[j] << " actual:" << (unsigned int)after[j] << std::endl;
					passedFlag = false;
				}
			}
		}
	}
	alignedFree(_srcVectorMul);
	alignedFree(_srcVectorDiv);
	alignedFree(converted);
	alignedFree(originalFloat);
	return passedFlag;
}

int main()
{
	if (checkFeatureSupport() == false)
	{
		return 1;
	}
	verifyMultiply();
}
<commit_msg>clean up the code   * use repeat intrinsic<commit_after>#include <iostream>
#include <iomanip>
#include <malloc.h>
#ifdef _MSC_VER
#include <cstdlib>
#define alignedMalloc(size,align)	_aligned_malloc(size,align)
#define alignedFree(ptr)			_aligned_free(ptr)
#elif defined (__GNUC__)
#define alignedMalloc(size,align)	memalign(align,size)
#define alignedFree(ptr)			free(ptr)
#endif
#include "floatMul.h"
#include "featureSupport.h"
#include "simdUtils.h"

const int ALIGN   = 16; // alignment step for SSE
const int cWidth  = 256;
const int cHeight = cWidth;
const int cSize   = cHeight * cWidth;

half4 compressToHalf4(uint4 integer, float4 srcVector)
{
	float4 dstFloat4;
	dstFloat4 = convert_uint4_float4(integer);
	dstFloat4 = multiply_float4(dstFloat4, srcVector);
	return convert_float4_half4(dstFloat4);
}

uint4 uncompressToInt4(half4 halfVector, float4 srcVector)
{
	float4 dstFloat4;
	dstFloat4 = convert_half4_float4(halfVector);
	dstFloat4 = multiply_float4(dstFloat4, srcVector);
	return convert_float4_uint4(dstFloat4);
}

bool verifyMultiply()
{
	float _originalFloat[] = {1.1f,  1.49f, 1.50f, 1.99f, 1.0000001f, 1.4999999f, 1.5000000f, 1.9999999f, };
	float* originalFloat = reinterpret_cast<float*>(alignedMalloc(8*sizeof(float),ALIGN));
	unsigned int* converted = reinterpret_cast<unsigned int*>(alignedMalloc(8*sizeof(float),ALIGN));
	for (int i = 0;i < 8;i++)
	{
		originalFloat[i] = _originalFloat[i];
	}

	float4 srcFloat1 = load_float4((const float*)originalFloat);
	float4 srcFloat2 = load_float4((const float*)&originalFloat[4]);
	uint4 dstInt1 = convert_float4_uint4(srcFloat1);
	uint4 dstInt2 = convert_float4_uint4(srcFloat2);
	store_uint4(&converted[0], dstInt1);
	store_uint4(&converted[4], dstInt2);

	std::cout << originalFloat[0] << '\t' << originalFloat[1] << '\t' << originalFloat[2] << '\t' << originalFloat[3] << std::endl;
	std::cout << converted[0]     << '\t' << converted[1]     << '\t' << converted[2]     << '\t' << converted[3]     << std::endl;
	std::cout << originalFloat[4] << '\t' << originalFloat[5] << '\t' << originalFloat[6] << '\t' << originalFloat[7] << std::endl;
	std::cout << converted[4]     << '\t' << converted[5]     << '\t' << converted[6]     << '\t' << converted[7]     << std::endl;

	const unsigned char cParallel = 8;
	unsigned char _original[] = {0, 1, 2, 3, 4, 5, 6, 7, };
	uchar8 step     = load_uchar8_repeat(cParallel);
	uchar8 original = load_uchar8(_original);
	char before[cParallel], after[cParallel];
	bool passedFlag = true;
	for (int src = 1;src < 256;src++)
	{
		float4 srcVectorDiv = load_float4_copy(1.0f/(float)src);
		float4 srcVectorMul = load_float4_copy(     (float)src);
		uchar8 dst = original;
		for (int i = 0;i <= 256 - cParallel;i += cParallel)
		{
			// compress the gain
			ushort8 dstShort8     = convert_uchar8_ushort8(dst);
			uint4 dstIntegerLow4  = convert_ushort8_lo_uint4(dstShort8);
			uint4 dstIntegerHigh4 = convert_ushort8_hi_uint4(dstShort8);
			half4 compressLow4    = compressToHalf4(dstIntegerLow4,  srcVectorDiv);
			half4 compressHigh4   = compressToHalf4(dstIntegerHigh4, srcVectorDiv);

			// uncompress the gain
			dstIntegerLow4  = uncompressToInt4(compressLow4,  srcVectorMul);
			dstIntegerHigh4 = uncompressToInt4(compressHigh4, srcVectorMul);
			dstShort8       = convert_uint4_ushort8(dstIntegerLow4, dstIntegerHigh4);
			uchar8 resultChar8;
			resultChar8     = convert_ushort8_uchar8(dstShort8);

			store_uchar8((void*)before, dst);
			store_uchar8((void*)after,  resultChar8);
			dst = dst + step;
			for (int j = 0;j < cParallel;j++)
			{
				if (before[j] != after[j])
				{
					std::cerr << "error: src:" << src << " expected:" << (unsigned int)before[j] << " actual:" << (unsigned int)after[j] << std::endl;
					passedFlag = false;
				}
			}
		}
	}
	alignedFree(converted);
	alignedFree(originalFloat);
	return passedFlag;
}

int main()
{
	if (checkFeatureSupport() == false)
	{
		return 1;
	}
	verifyMultiply();
}
<|endoftext|>