<commit_before>#include "index/ElementStore.hpp"
#include "mapcss/StyleProvider.hpp"

#include <boost/test/unit_test.hpp>

#include "test_utils/MapCssUtils.hpp"

using namespace utymap::index;
using namespace utymap::mapcss;

struct Index_ElementStoreFixture
{
    Index_ElementStoreFixture() :
        stringTablePtr(new StringTable("")),
        styleProviderPtr(nullptr)
    {
        BOOST_TEST_MESSAGE("setup fixture");
    }

    ~Index_ElementStoreFixture()
    {
        BOOST_TEST_MESSAGE("teardown fixture");
        delete stringTablePtr;
        delete styleProviderPtr;
        std::remove("string.idx");
        std::remove("string.dat");
    }

    StringTable* stringTablePtr;
    StyleProvider* styleProviderPtr;
};

BOOST_FIXTURE_TEST_SUITE(Index_ElementStore, Index_ElementStoreFixture)

BOOST_AUTO_TEST_CASE(GivenBigWay_WhenStore_GeometryIsClipped)
{
    styleProviderPtr = MapCssUtils::createStyleProviderFromString(*stringTablePtr,
        "way|z1[test=Foo] { key:val; }");

    // TODO
}

BOOST_AUTO_TEST_SUITE_END()<commit_msg>testing: commit progress on ElementStoreTest<commit_after>#include "entities/Element.hpp"
#include "entities/Node.hpp"
#include "entities/Way.hpp"
#include "entities/Area.hpp"
#include "entities/Relation.hpp"
#include "index/ElementStore.hpp"
#include "mapcss/StyleProvider.hpp"

#include <boost/test/unit_test.hpp>

#include "test_utils/MapCssUtils.hpp"

using namespace utymap::entities;
using namespace utymap::index;
using namespace utymap::mapcss;

class TestElementStore : public ElementStore
{
public:
    TestElementStore(const StyleProvider& styleProvider, StringTable& stringTable) :
        ElementStore(styleProvider, stringTable),
        lastElement(),
        lastQuadKey()
    {
    }

    Element lastElement;
    utymap::QuadKey lastQuadKey;

protected:
    void store(const Element& element, const utymap::QuadKey& quadKey)
    {
        lastElement = element;
        lastQuadKey = quadKey;
    }
};

struct Index_ElementStoreFixture
{
    Index_ElementStoreFixture() :
        stringTablePtr(new StringTable("")),
        styleProviderPtr(nullptr),
        elementStorePtr()
    {
        BOOST_TEST_MESSAGE("setup fixture");
    }

    ~Index_ElementStoreFixture()
    {
        BOOST_TEST_MESSAGE("teardown fixture");
        delete elementStorePtr;
        delete styleProviderPtr;
        delete stringTablePtr;
        std::remove("string.idx");
        std::remove("string.dat");
    }

    void createElementStore(std::string stylesheet)
    {
        styleProviderPtr = MapCssUtils::createStyleProviderFromString(*stringTablePtr, stylesheet);
        elementStorePtr = new TestElementStore(*styleProviderPtr, *stringTablePtr);
    }

    StringTable* stringTablePtr;
    StyleProvider* styleProviderPtr;
    TestElementStore* elementStorePtr;
};

BOOST_FIXTURE_TEST_SUITE(Index_ElementStore, Index_ElementStoreFixture)

BOOST_AUTO_TEST_CASE(GivenBigWay_WhenStore_GeometryIsClipped)
{
    Way way;
    createElementStore("way|z1[test=Foo] { key:val; }");

    // TODO
}

BOOST_AUTO_TEST_SUITE_END()<|endoftext|>


<commit_before>// Copyright 2016-2018 Francesco Biscani (bluescarni@gmail.com)
//
// This file is part of the mp++ library.
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <cstddef>
#include <gmp.h>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>

#include <mp++/integer.hpp>

#include "test_utils.hpp"

#define CATCH_CONFIG_MAIN
#include "catch.hpp"

static int ntries = 1000;

using namespace mppp;
using namespace mppp_test;

using sizes = std::tuple<std::integral_constant<std::size_t, 1>, std::integral_constant<std::size_t, 2>,
                         std::integral_constant<std::size_t, 3>, std::integral_constant<std::size_t, 6>,
                         std::integral_constant<std::size_t, 10>>;

struct probab_prime_p_tester {
    template <typename S>
    inline void operator()(const S &) const
    {
        using integer = integer<S::value>;
        mpz_raii m1;
        integer n1;
        REQUIRE((probab_prime_p(n1) == ::mpz_probab_prime_p(&m1.m_mpz, 25)));
        REQUIRE((n1.probab_prime_p() == ::mpz_probab_prime_p(&m1.m_mpz, 25)));
        ::mpz_set_ui(&m1.m_mpz, 1u);
        n1 = integer(1);
        REQUIRE((probab_prime_p(n1, 12) == ::mpz_probab_prime_p(&m1.m_mpz, 25)));
        REQUIRE((n1.probab_prime_p(12) == ::mpz_probab_prime_p(&m1.m_mpz, 25)));
        ::mpz_set_ui(&m1.m_mpz, 123u);
        n1 = integer(123);
        REQUIRE((probab_prime_p(n1) == ::mpz_probab_prime_p(&m1.m_mpz, 25)));
        REQUIRE((n1.probab_prime_p() == ::mpz_probab_prime_p(&m1.m_mpz, 25)));
        // Couple of sanity checks.
        REQUIRE((probab_prime_p(integer{17}) != 0));
        REQUIRE((probab_prime_p(integer{49979687ll}) != 0));
        REQUIRE((probab_prime_p(integer{128}) == 0));
        // Test errors.
        REQUIRE_THROWS_PREDICATE(probab_prime_p(n1, 0), std::invalid_argument, [](const std::invalid_argument &ex) {
            return std::string(ex.what())
                   == "The number of primality tests must be at least 1, but a value of "
                      "0 was provided instead";
        });
        REQUIRE_THROWS_PREDICATE(n1.probab_prime_p(-1), std::invalid_argument, [](const std::invalid_argument &ex) {
            return std::string(ex.what())
                   == "The number of primality tests must be at least 1, but a value of "
                      "-1 was provided instead";
        });
        n1 = integer(-123);
        REQUIRE_THROWS_PREDICATE(probab_prime_p(n1), std::invalid_argument, [](const std::invalid_argument &ex) {
            return std::string(ex.what()) == "Cannot run primality tests on the negative number -123";
        });
        REQUIRE_THROWS_PREDICATE(n1.probab_prime_p(), std::invalid_argument, [](const std::invalid_argument &ex) {
            return std::string(ex.what()) == "Cannot run primality tests on the negative number -123";
        });
    }
};

TEST_CASE("probab_prime_p")
{
    tuple_for_each(sizes{}, probab_prime_p_tester{});
}
<commit_msg>Fix warning due to unused variable in a test.<commit_after>// Copyright 2016-2018 Francesco Biscani (bluescarni@gmail.com)
//
// This file is part of the mp++ library.
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <cstddef>
#include <gmp.h>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>

#include <mp++/integer.hpp>

#include "test_utils.hpp"

#define CATCH_CONFIG_MAIN
#include "catch.hpp"

using namespace mppp;
using namespace mppp_test;

using sizes = std::tuple<std::integral_constant<std::size_t, 1>, std::integral_constant<std::size_t, 2>,
                         std::integral_constant<std::size_t, 3>, std::integral_constant<std::size_t, 6>,
                         std::integral_constant<std::size_t, 10>>;

struct probab_prime_p_tester {
    template <typename S>
    inline void operator()(const S &) const
    {
        using integer = integer<S::value>;
        mpz_raii m1;
        integer n1;
        REQUIRE((probab_prime_p(n1) == ::mpz_probab_prime_p(&m1.m_mpz, 25)));
        REQUIRE((n1.probab_prime_p() == ::mpz_probab_prime_p(&m1.m_mpz, 25)));
        ::mpz_set_ui(&m1.m_mpz, 1u);
        n1 = integer(1);
        REQUIRE((probab_prime_p(n1, 12) == ::mpz_probab_prime_p(&m1.m_mpz, 25)));
        REQUIRE((n1.probab_prime_p(12) == ::mpz_probab_prime_p(&m1.m_mpz, 25)));
        ::mpz_set_ui(&m1.m_mpz, 123u);
        n1 = integer(123);
        REQUIRE((probab_prime_p(n1) == ::mpz_probab_prime_p(&m1.m_mpz, 25)));
        REQUIRE((n1.probab_prime_p() == ::mpz_probab_prime_p(&m1.m_mpz, 25)));
        // Couple of sanity checks.
        REQUIRE((probab_prime_p(integer{17}) != 0));
        REQUIRE((probab_prime_p(integer{49979687ll}) != 0));
        REQUIRE((probab_prime_p(integer{128}) == 0));
        // Test errors.
        REQUIRE_THROWS_PREDICATE(probab_prime_p(n1, 0), std::invalid_argument, [](const std::invalid_argument &ex) {
            return std::string(ex.what())
                   == "The number of primality tests must be at least 1, but a value of "
                      "0 was provided instead";
        });
        REQUIRE_THROWS_PREDICATE(n1.probab_prime_p(-1), std::invalid_argument, [](const std::invalid_argument &ex) {
            return std::string(ex.what())
                   == "The number of primality tests must be at least 1, but a value of "
                      "-1 was provided instead";
        });
        n1 = integer(-123);
        REQUIRE_THROWS_PREDICATE(probab_prime_p(n1), std::invalid_argument, [](const std::invalid_argument &ex) {
            return std::string(ex.what()) == "Cannot run primality tests on the negative number -123";
        });
        REQUIRE_THROWS_PREDICATE(n1.probab_prime_p(), std::invalid_argument, [](const std::invalid_argument &ex) {
            return std::string(ex.what()) == "Cannot run primality tests on the negative number -123";
        });
    }
};

TEST_CASE("probab_prime_p")
{
    tuple_for_each(sizes{}, probab_prime_p_tester{});
}
<|endoftext|>


<commit_before>#include <GL/glew.h>
#include "FAST/Utility.hpp"
#include "FAST/DeviceManager.hpp"
#include "FAST/Visualization/View.hpp"
#include "FAST/Utility.hpp"
#include <QCursor>
#include <boost/thread/lock_guard.hpp>
#include "MeshRenderer.hpp"
#include "FAST/SceneGraph.hpp"

namespace fast {

void MeshRenderer::addInputConnection(ProcessObjectPort port) {
    uint nr = getNrOfInputData();
    if(nr > 0)
        createInputPort<Mesh>(nr);
    releaseInputAfterExecute(nr, false);
    setInputConnection(nr, port);
    mIsModified = true;
}

void MeshRenderer::addInputConnection(ProcessObjectPort port, Color color, float opacity) {
    addInputConnection(port);
    mInputColors[port] = color;
    mInputOpacities[port] = opacity;
}

MeshRenderer::MeshRenderer() : Renderer() {
    mDefaultOpacity = 1;
    mDefaultColor = Color::Green();
    mDefaultSpecularReflection = 0.8f;
    createInputPort<Mesh>(0, false);
}

void MeshRenderer::execute() {
    boost::lock_guard<boost::mutex> lock(mMutex);
    for(uint inputNr = 0; inputNr < getNrOfInputData(); inputNr++) {
        Mesh::pointer input = getStaticInputData<Mesh>(inputNr);
        mMeshToRender[inputNr] = input;
    }
}

void MeshRenderer::draw() {
    boost::lock_guard<boost::mutex> lock(mMutex);

    glEnable(GL_NORMALIZE);
    glShadeModel(GL_SMOOTH);
    glEnable(GL_LIGHTING);

    boost::unordered_map<uint, Mesh::pointer>::iterator it;
    for(it = mMeshToRender.begin(); it != mMeshToRender.end(); it++) {
        Mesh::pointer surfaceToRender = it->second;

        if(surfaceToRender->getDimensions() != 3)
        	continue;

        // Draw the triangles in the VBO
        AffineTransformation::pointer transform = SceneGraph::getAffineTransformationFromData(surfaceToRender);

        glPushMatrix();
        glMultMatrixf(transform->data());

        float opacity = mDefaultOpacity;
        Color color = mDefaultColor;
        ProcessObjectPort port = getInputPort(it->first);
        if(mInputOpacities.count(port) > 0) {
            opacity = mInputOpacities[port];
        }
        if(mInputColors.count(port) > 0) {
            color = mInputColors[port];
        }

        // Set material properties
        if(opacity < 1) {
            // Enable transparency
            glEnable(GL_BLEND);
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        }
        GLfloat GLcolor[] = { color.getRedValue(), color.getGreenValue(), color.getBlueValue(), opacity };
        glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, GLcolor);
        GLfloat specReflection[] = { mDefaultSpecularReflection, mDefaultSpecularReflection, mDefaultSpecularReflection, 1.0f };
        glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specReflection);
        GLfloat shininess[] = { 16.0f };
        glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, shininess);

        VertexBufferObjectAccess::pointer access = surfaceToRender->getVertexBufferObjectAccess(ACCESS_READ, getMainDevice());
        GLuint* VBO_ID = access->get();

        // Normal Buffer
        glBindBuffer(GL_ARRAY_BUFFER, *VBO_ID);
        glEnableClientState(GL_VERTEX_ARRAY);
        glEnableClientState(GL_NORMAL_ARRAY);

        glVertexPointer(3, GL_FLOAT, 24, 0);
        glNormalPointer(GL_FLOAT, 24, (float*)(sizeof(GLfloat)*3));

        glDrawArrays(GL_TRIANGLES, 0, surfaceToRender->getNrOfTriangles()*3);

        // Release buffer
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glDisableClientState(GL_VERTEX_ARRAY);
        glDisableClientState(GL_NORMAL_ARRAY);
        if(opacity < 1) {
            // Disable transparency
            glDisable(GL_BLEND);
        }
        glPopMatrix();
    }

    glDisable(GL_LIGHTING);
    glDisable(GL_NORMALIZE);
    glColor3f(1.0f, 1.0f, 1.0f); // Reset color
}

void MeshRenderer::draw2D(
                cl::BufferGL PBO,
                uint width,
                uint height,
                Eigen::Transform<float, 3, Eigen::Affine> pixelToViewportTransform,
                float PBOspacing,
                Vector2f translation
        ) {
    boost::lock_guard<boost::mutex> lock(mMutex);

    OpenCLDevice::pointer device = getMainDevice();
    cl::CommandQueue queue = device->getCommandQueue();
    std::vector<cl::Memory> v;
    v.push_back(PBO);
    queue.enqueueAcquireGLObjects(&v);

    // Transfer PBO pixels to host or map?
    float* pixels = (float*)queue.enqueueMapBuffer(PBO, CL_TRUE, CL_MAP_WRITE, 0, width*height*sizeof(float)*4);

    boost::unordered_map<uint, Mesh::pointer>::iterator it;
    for(it = mMeshToRender.begin(); it != mMeshToRender.end(); it++) {
    	Mesh::pointer mesh = it->second;
    	if(mesh->getDimensions() != 2) // Mesh must be 2D
    		continue;

		Color color = mDefaultColor;
        ProcessObjectPort port = getInputPort(it->first);
        if(mInputColors.count(port) > 0) {
            color = mInputColors[port];
        }

    	MeshAccess::pointer access = mesh->getMeshAccess(ACCESS_READ);
        std::vector<VectorXui> lines = access->getLines();
        std::vector<MeshVertex> vertices = access->getVertices();

        // Draw each line
        for(int i = 0; i < lines.size(); ++i) {
        	Vector2ui line = lines[i];
        	Vector2f a = vertices[line.x()].getPosition();
        	Vector2f b = vertices[line.y()].getPosition();
        	Vector2f direction = b - a;
        	float lengthInPixels = ceil(direction.norm() / PBOspacing);

        	// Draw the line
        	for(int j = 0; j <= lengthInPixels; ++j) {
        		Vector2f positionInMM = a + direction*((float)j/lengthInPixels);
        		Vector2f positionInPixels = positionInMM / PBOspacing;

        		int x = round(positionInPixels.x());
        		int y = round(positionInPixels.y());
        		y = height - 1 - y;
        		if(x < 0 || y < 0 || x >= width || y >= height)
        			continue;

        		pixels[4*(x + y*width)] = color.getRedValue();
        		pixels[4*(x + y*width) + 1] = color.getGreenValue();
        		pixels[4*(x + y*width) + 2] = color.getBlueValue();
        	}
        }
    }

    queue.enqueueUnmapMemObject(PBO, pixels);
    queue.enqueueReleaseGLObjects(&v);
    queue.finish();
}

BoundingBox MeshRenderer::getBoundingBox() {
    std::vector<Vector3f> coordinates;
    for(uint i = 0; i < getNrOfInputData(); i++) {
        BoundingBox transformedBoundingBox = mMeshToRender[i]->getTransformedBoundingBox();
        MatrixXf corners = transformedBoundingBox.getCorners();
        for(uint j = 0; j < 8; j++) {
            coordinates.push_back((Vector3f)corners.row(j));
        }
    }
    return BoundingBox(coordinates);
}

void MeshRenderer::setDefaultColor(Color color) {
    mDefaultColor = color;
}

void MeshRenderer::setColor(ProcessObjectPort port, Color color) {
    mInputColors[port] = color;
}

void MeshRenderer::setOpacity(ProcessObjectPort port, float opacity) {
    mInputOpacities[port] = opacity;
}

void MeshRenderer::setDefaultOpacity(float opacity) {
    mDefaultOpacity = opacity;
    if(mDefaultOpacity > 1) {
        mDefaultOpacity = 1;
    } else if(mDefaultOpacity < 0) {
        mDefaultOpacity = 0;
    }
}

void MeshRenderer::setDefaultSpecularReflection(float specularReflection) {
    mDefaultSpecularReflection = specularReflection;
}

} // namespace fast
<commit_msg>created a work around for an nvidia bug in the mesh renderer<commit_after>#include <GL/glew.h>
#include "FAST/Utility.hpp"
#include "FAST/DeviceManager.hpp"
#include "FAST/Visualization/View.hpp"
#include "FAST/Utility.hpp"
#include <QCursor>
#include <boost/thread/lock_guard.hpp>
#include <boost/shared_array.hpp>
#include "MeshRenderer.hpp"
#include "FAST/SceneGraph.hpp"

namespace fast {

void MeshRenderer::addInputConnection(ProcessObjectPort port) {
    uint nr = getNrOfInputData();
    if(nr > 0)
        createInputPort<Mesh>(nr);
    releaseInputAfterExecute(nr, false);
    setInputConnection(nr, port);
    mIsModified = true;
}

void MeshRenderer::addInputConnection(ProcessObjectPort port, Color color, float opacity) {
    addInputConnection(port);
    mInputColors[port] = color;
    mInputOpacities[port] = opacity;
}

MeshRenderer::MeshRenderer() : Renderer() {
    mDefaultOpacity = 1;
    mDefaultColor = Color::Green();
    mDefaultSpecularReflection = 0.8f;
    createInputPort<Mesh>(0, false);
}

void MeshRenderer::execute() {
    boost::lock_guard<boost::mutex> lock(mMutex);
    for(uint inputNr = 0; inputNr < getNrOfInputData(); inputNr++) {
        Mesh::pointer input = getStaticInputData<Mesh>(inputNr);
        mMeshToRender[inputNr] = input;
    }
}

void MeshRenderer::draw() {
    boost::lock_guard<boost::mutex> lock(mMutex);

    glEnable(GL_NORMALIZE);
    glShadeModel(GL_SMOOTH);
    glEnable(GL_LIGHTING);

    boost::unordered_map<uint, Mesh::pointer>::iterator it;
    for(it = mMeshToRender.begin(); it != mMeshToRender.end(); it++) {
        Mesh::pointer surfaceToRender = it->second;

        if(surfaceToRender->getDimensions() != 3)
        	continue;

        // Draw the triangles in the VBO
        AffineTransformation::pointer transform = SceneGraph::getAffineTransformationFromData(surfaceToRender);

        glPushMatrix();
        glMultMatrixf(transform->data());

        float opacity = mDefaultOpacity;
        Color color = mDefaultColor;
        ProcessObjectPort port = getInputPort(it->first);
        if(mInputOpacities.count(port) > 0) {
            opacity = mInputOpacities[port];
        }
        if(mInputColors.count(port) > 0) {
            color = mInputColors[port];
        }

        // Set material properties
        if(opacity < 1) {
            // Enable transparency
            glEnable(GL_BLEND);
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        }
        GLfloat GLcolor[] = { color.getRedValue(), color.getGreenValue(), color.getBlueValue(), opacity };
        glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, GLcolor);
        GLfloat specReflection[] = { mDefaultSpecularReflection, mDefaultSpecularReflection, mDefaultSpecularReflection, 1.0f };
        glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specReflection);
        GLfloat shininess[] = { 16.0f };
        glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, shininess);

        VertexBufferObjectAccess::pointer access = surfaceToRender->getVertexBufferObjectAccess(ACCESS_READ, getMainDevice());
        GLuint* VBO_ID = access->get();

        // Normal Buffer
        glBindBuffer(GL_ARRAY_BUFFER, *VBO_ID);
        glEnableClientState(GL_VERTEX_ARRAY);
        glEnableClientState(GL_NORMAL_ARRAY);

        glVertexPointer(3, GL_FLOAT, 24, 0);
        glNormalPointer(GL_FLOAT, 24, (float*)(sizeof(GLfloat)*3));

        glDrawArrays(GL_TRIANGLES, 0, surfaceToRender->getNrOfTriangles()*3);

        // Release buffer
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glDisableClientState(GL_VERTEX_ARRAY);
        glDisableClientState(GL_NORMAL_ARRAY);
        if(opacity < 1) {
            // Disable transparency
            glDisable(GL_BLEND);
        }
        glPopMatrix();
    }

    glDisable(GL_LIGHTING);
    glDisable(GL_NORMALIZE);
    glColor3f(1.0f, 1.0f, 1.0f); // Reset color
}

void MeshRenderer::draw2D(
                cl::BufferGL PBO,
                uint width,
                uint height,
                Eigen::Transform<float, 3, Eigen::Affine> pixelToViewportTransform,
                float PBOspacing,
                Vector2f translation
        ) {
    boost::lock_guard<boost::mutex> lock(mMutex);

    OpenCLDevice::pointer device = getMainDevice();
    cl::CommandQueue queue = device->getCommandQueue();
    std::vector<cl::Memory> v;
    v.push_back(PBO);
    queue.enqueueAcquireGLObjects(&v);

    // Map would probably be better here, but doesn't work on NVIDIA, segfault surprise!
    //float* pixels = (float*)queue.enqueueMapBuffer(PBO, CL_TRUE, CL_MAP_WRITE, 0, width*height*sizeof(float)*4);
    boost::shared_array<float> pixels(new float[width*height*sizeof(float)*4]);
    queue.enqueueReadBuffer(PBO, CL_TRUE, 0, width*height*4*sizeof(float), pixels.get());

    boost::unordered_map<uint, Mesh::pointer>::iterator it;
    for(it = mMeshToRender.begin(); it != mMeshToRender.end(); it++) {
    	Mesh::pointer mesh = it->second;
    	if(mesh->getDimensions() != 2) // Mesh must be 2D
    		continue;

		Color color = mDefaultColor;
        ProcessObjectPort port = getInputPort(it->first);
        if(mInputColors.count(port) > 0) {
            color = mInputColors[port];
        }

    	MeshAccess::pointer access = mesh->getMeshAccess(ACCESS_READ);
        std::vector<VectorXui> lines = access->getLines();
        std::vector<MeshVertex> vertices = access->getVertices();

        // Draw each line
        for(int i = 0; i < lines.size(); ++i) {
        	Vector2ui line = lines[i];
        	Vector2f a = vertices[line.x()].getPosition();
        	Vector2f b = vertices[line.y()].getPosition();
        	Vector2f direction = b - a;
        	float lengthInPixels = ceil(direction.norm() / PBOspacing);

        	// Draw the line
        	for(int j = 0; j <= lengthInPixels; ++j) {
        		Vector2f positionInMM = a + direction*((float)j/lengthInPixels);
        		Vector2f positionInPixels = positionInMM / PBOspacing;

        		int x = round(positionInPixels.x());
        		int y = round(positionInPixels.y());
        		y = height - 1 - y;
        		if(x < 0 || y < 0 || x >= width || y >= height)
        			continue;

        		pixels[4*(x + y*width)] = color.getRedValue();
        		pixels[4*(x + y*width) + 1] = color.getGreenValue();
        		pixels[4*(x + y*width) + 2] = color.getBlueValue();
        	}
        }
    }

    //queue.enqueueUnmapMemObject(PBO, pixels);
    queue.enqueueWriteBuffer(PBO, CL_TRUE, 0, width*height*4*sizeof(float), pixels.get());
    queue.enqueueReleaseGLObjects(&v);
}

BoundingBox MeshRenderer::getBoundingBox() {
    std::vector<Vector3f> coordinates;
    for(uint i = 0; i < getNrOfInputData(); i++) {
        BoundingBox transformedBoundingBox = mMeshToRender[i]->getTransformedBoundingBox();
        MatrixXf corners = transformedBoundingBox.getCorners();
        for(uint j = 0; j < 8; j++) {
            coordinates.push_back((Vector3f)corners.row(j));
        }
    }
    return BoundingBox(coordinates);
}

void MeshRenderer::setDefaultColor(Color color) {
    mDefaultColor = color;
}

void MeshRenderer::setColor(ProcessObjectPort port, Color color) {
    mInputColors[port] = color;
}

void MeshRenderer::setOpacity(ProcessObjectPort port, float opacity) {
    mInputOpacities[port] = opacity;
}

void MeshRenderer::setDefaultOpacity(float opacity) {
    mDefaultOpacity = opacity;
    if(mDefaultOpacity > 1) {
        mDefaultOpacity = 1;
    } else if(mDefaultOpacity < 0) {
        mDefaultOpacity = 0;
    }
}

void MeshRenderer::setDefaultSpecularReflection(float specularReflection) {
    mDefaultSpecularReflection = specularReflection;
}

} // namespace fast
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2019 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/planning/tasks/deciders/speed_bounds_decider/speed_bounds_decider.h"

#include <string>
#include <tuple>
#include <vector>

#include "modules/common/vehicle_state/vehicle_state_provider.h"
#include "modules/planning/common/change_lane_decider.h"
#include "modules/planning/common/path/path_data.h"
#include "modules/planning/common/planning_context.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/common/st_graph_data.h"
#include "modules/planning/tasks/deciders/decider_rule_based_stop.h"
#include "modules/planning/tasks/deciders/speed_bounds_decider/speed_limit_decider.h"
#include "modules/planning/tasks/deciders/speed_bounds_decider/st_boundary_mapper.h"

namespace apollo {
namespace planning {

using apollo::common::ErrorCode;
using apollo::common::SLPoint;
using apollo::common::Status;
using apollo::common::TrajectoryPoint;
using apollo::planning_internal::StGraphBoundaryDebug;
using apollo::planning_internal::STGraphDebug;

SpeedBoundsDecider::SpeedBoundsDecider(const TaskConfig &config)
    : Decider(config) {
  CHECK(config.has_speed_bounds_decider_config());
  speed_bounds_config_ = config.speed_bounds_decider_config();
  SetName("SpeedBoundsDecider");
}

Status SpeedBoundsDecider::Process(
    Frame *const frame, ReferenceLineInfo *const reference_line_info) {
  // retrieve data from frame and reference_line_info
  const SLBoundary &adc_sl_boundary = reference_line_info->AdcSlBoundary();
  const PathData &path_data = reference_line_info->path_data();
  const TrajectoryPoint &init_point = frame->PlanningStartPoint();
  const ReferenceLine &reference_line = reference_line_info->reference_line();
  PathDecision *const path_decision = reference_line_info->path_decision();

  // 1. Rule_based speed planning configurations for different traffic scenarios
  if (FLAGS_enable_nonscenario_side_pass) {
    double stop_s_on_pathdata = 0.0;
    bool set_stop_fence = false;
    const auto &side_pass_info = PlanningContext::side_pass_info();
    auto *mutable_side_pass_info = PlanningContext::mutable_side_pass_info();
    if (side_pass_info.change_lane_stop_flag) {
      // Check if stop at last frame stop fence
      if (CheckADCStop(*reference_line_info,
                       side_pass_info.change_lane_stop_path_point)) {
        if (ChangeLaneDecider::IsClearToChangeLane(reference_line_info)) {
          mutable_side_pass_info->check_clear_flag = true;
        } else if (CheckSidePassStop(path_data, &stop_s_on_pathdata)) {
          set_stop_fence = BuildSidePassStopFence(
              path_data, stop_s_on_pathdata,
              &(mutable_side_pass_info->change_lane_stop_path_point), frame,
              reference_line_info);
        }

      } else {
        if (CheckSidePassStop(path_data, &stop_s_on_pathdata)) {
          set_stop_fence = BuildSidePassStopFence(
              path_data, stop_s_on_pathdata,
              &(mutable_side_pass_info->change_lane_stop_path_point), frame,
              reference_line_info);
        }
      }
    } else {
      if (!side_pass_info.check_clear_flag &&
          CheckSidePassStop(path_data, &stop_s_on_pathdata)) {
        set_stop_fence = BuildSidePassStopFence(
            path_data, stop_s_on_pathdata,
            &(mutable_side_pass_info->change_lane_stop_path_point), frame,
            reference_line_info);
      }
      if (side_pass_info.check_clear_flag &&
          CheckClearDone(*reference_line_info,
                         side_pass_info.change_lane_stop_path_point)) {
        mutable_side_pass_info->check_clear_flag = false;
      }
    }
    mutable_side_pass_info->change_lane_stop_flag = set_stop_fence;
  }

  // 2. Map obstacles into st graph
  StBoundaryMapper boundary_mapper(adc_sl_boundary, speed_bounds_config_,
                                   reference_line, path_data,
                                   speed_bounds_config_.total_path_length(),
                                   speed_bounds_config_.total_time(),
                                   reference_line_info_->IsChangeLanePath());

  path_decision->EraseStBoundaries();
  if (boundary_mapper.CreateStBoundary(path_decision).code() ==
      ErrorCode::PLANNING_ERROR) {
    const std::string msg = "Mapping obstacle failed.";
    AERROR << msg;
    return Status(ErrorCode::PLANNING_ERROR, msg);
  }

  std::vector<const STBoundary *> boundaries;
  for (auto *obstacle : path_decision->obstacles().Items()) {
    auto id = obstacle->Id();
    if (!obstacle->st_boundary().IsEmpty()) {
      if (obstacle->st_boundary().boundary_type() ==
          STBoundary::BoundaryType::KEEP_CLEAR) {
        path_decision->Find(id)->SetBlockingObstacle(false);
      } else {
        path_decision->Find(id)->SetBlockingObstacle(true);
      }
      boundaries.push_back(&obstacle->st_boundary());
    }
  }

  // 3. Create speed limit along path
  SpeedLimitDecider speed_limit_decider(adc_sl_boundary, speed_bounds_config_,
                                        reference_line, path_data);

  SpeedLimit speed_limit;
  if (!speed_limit_decider
           .GetSpeedLimits(path_decision->obstacles(), &speed_limit)
           .ok()) {
    std::string msg("Getting speed limits failed!");
    AERROR << msg;
    return Status(ErrorCode::PLANNING_ERROR, msg);
  }

  // 3. Get path_length as s axis search bound in st graph
  const double path_data_length = path_data.discretized_path().Length();
  const double path_length_by_conf = speed_bounds_config_.total_path_length();

  // 4. Get time duration as t axis search bound in st graph
  const double total_time_by_conf = speed_bounds_config_.total_time();

  // Load generated st graph data back to frame
  StGraphData *st_graph_data = reference_line_info_->mutable_st_graph_data();

  // Add a st_graph debug info and save the pointer to st_graph_data for
  // optimizer logging
  auto *debug = reference_line_info_->mutable_debug();
  STGraphDebug *st_graph_debug = debug->mutable_planning_data()->add_st_graph();

  st_graph_data->LoadData(boundaries, init_point, speed_limit, path_data_length,
                          path_length_by_conf, total_time_by_conf,
                          st_graph_debug);

  // Create and record st_graph debug info
  RecordSTGraphDebug(*st_graph_data, st_graph_debug);

  return Status::OK();
}  // namespace planning

// @brief Check if necessary to set stop fence used for nonscenario side pass
bool SpeedBoundsDecider::CheckSidePassStop(const PathData &path_data,
                                           double *stop_s_on_pathdata) {
  const std::vector<std::tuple<double, PathData::PathPointType, double>>
      &path_point_decision_guide = path_data.path_point_decision_guide();
  PathData::PathPointType last_path_point_type =
      PathData::PathPointType::UNKNOWN;
  for (const auto &point_guide : path_point_decision_guide) {
    if (last_path_point_type == PathData::PathPointType::IN_LANE &&
        std::get<1>(point_guide) != PathData::PathPointType::IN_LANE) {
      *stop_s_on_pathdata = std::get<0>(point_guide);
      return true;
    }
    last_path_point_type = std::get<1>(point_guide);
  }
  return false;
}

// @brief Set stop fence for side pass
bool SpeedBoundsDecider::BuildSidePassStopFence(
    const PathData &path_data, const double stop_s_on_pathdata,
    common::PathPoint *stop_pathpoint, Frame *const frame,
    ReferenceLineInfo *const reference_line_info) {
  CHECK_NOTNULL(frame);
  CHECK_NOTNULL(reference_line_info);

  if (!path_data.GetPathPointWithRefS(stop_s_on_pathdata, stop_pathpoint)) {
    return false;
  }

  const std::string stop_wall_id = "side_pass_stop";
  // TODO(Jinyun) load relavent surrounding obstacles
  std::vector<std::string> wait_for_obstacles;

  const auto &nearby_path = reference_line_info->reference_line().map_path();
  double stop_point_s = 0.0;
  double stop_point_l = 0.0;
  nearby_path.GetNearestPoint({stop_pathpoint->x(), stop_pathpoint->y()},
                              &stop_point_s, &stop_point_l);

  DeciderRuleBasedStop::BuildStopDecision(
      stop_wall_id, stop_point_s, 0.0,
      StopReasonCode::STOP_REASON_SIDEPASS_SAFETY, wait_for_obstacles, frame,
      reference_line_info);

  return true;
}

// @brief Check if ADV stop at a stop fence
bool SpeedBoundsDecider::CheckADCStop(
    const ReferenceLineInfo &reference_line_info,
    const common::PathPoint &stop_point) {
  const double adc_speed =
      common::VehicleStateProvider::Instance()->linear_velocity();
  if (adc_speed > speed_bounds_config_.max_adc_stop_speed()) {
    ADEBUG << "ADC not stopped: speed[" << adc_speed << "]";
    return false;
  }

  // check stop close enough to stop line of the stop_sign
  const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s();
  const auto &nearby_path = reference_line_info.reference_line().map_path();
  double stop_point_s = 0.0;
  double stop_point_l = 0.0;
  nearby_path.GetNearestPoint({stop_point.x(), stop_point.y()}, &stop_point_s,
                              &stop_point_l);

  const double distance_stop_line_to_adc_front_edge =
      stop_point_s - adc_front_edge_s;

  if (distance_stop_line_to_adc_front_edge >
      speed_bounds_config_.max_valid_stop_distance()) {
    ADEBUG << "not a valid stop. too far from stop line.";
    return false;
  }

  return true;
}

bool SpeedBoundsDecider::CheckClearDone(
    const ReferenceLineInfo &reference_line_info,
    const common::PathPoint &stop_point) {
  const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s();
  const double adc_back_edge_s = reference_line_info.AdcSlBoundary().start_s();
  const double adc_start_l = reference_line_info.AdcSlBoundary().start_l();
  const double adc_end_l = reference_line_info.AdcSlBoundary().end_l();
  double lane_left_width = 0.0;
  double lane_right_width = 0.0;
  reference_line_info.reference_line().GetLaneWidth(
      (adc_front_edge_s + adc_back_edge_s) / 2.0, &lane_left_width,
      &lane_right_width);
  SLPoint stop_sl_point;
  reference_line_info.reference_line().XYToSL({stop_point.x(), stop_point.y()},
                                              &stop_sl_point);
  // use distance to last stop point to determine if needed to check clear again
  if (adc_back_edge_s > stop_sl_point.s()) {
    if (adc_start_l > -lane_right_width || adc_end_l < lane_left_width) {
      return true;
    }
  }
  return false;
}

void SpeedBoundsDecider::RecordSTGraphDebug(
    const StGraphData &st_graph_data, STGraphDebug *st_graph_debug) const {
  if (!FLAGS_enable_record_debug || !st_graph_debug) {
    ADEBUG << "Skip record debug info";
    return;
  }

  for (const auto &boundary : st_graph_data.st_boundaries()) {
    auto boundary_debug = st_graph_debug->add_boundary();
    boundary_debug->set_name(boundary->id());
    switch (boundary->boundary_type()) {
      case STBoundary::BoundaryType::FOLLOW:
        boundary_debug->set_type(StGraphBoundaryDebug::ST_BOUNDARY_TYPE_FOLLOW);
        break;
      case STBoundary::BoundaryType::OVERTAKE:
        boundary_debug->set_type(
            StGraphBoundaryDebug::ST_BOUNDARY_TYPE_OVERTAKE);
        break;
      case STBoundary::BoundaryType::STOP:
        boundary_debug->set_type(StGraphBoundaryDebug::ST_BOUNDARY_TYPE_STOP);
        break;
      case STBoundary::BoundaryType::UNKNOWN:
        boundary_debug->set_type(
            StGraphBoundaryDebug::ST_BOUNDARY_TYPE_UNKNOWN);
        break;
      case STBoundary::BoundaryType::YIELD:
        boundary_debug->set_type(StGraphBoundaryDebug::ST_BOUNDARY_TYPE_YIELD);
        break;
      case STBoundary::BoundaryType::KEEP_CLEAR:
        boundary_debug->set_type(
            StGraphBoundaryDebug::ST_BOUNDARY_TYPE_KEEP_CLEAR);
        break;
    }

    for (const auto &point : boundary->points()) {
      auto point_debug = boundary_debug->add_point();
      point_debug->set_t(point.x());
      point_debug->set_s(point.y());
    }
  }

  for (const auto &point : st_graph_data.speed_limit().speed_limit_points()) {
    common::SpeedPoint speed_point;
    speed_point.set_s(point.first);
    speed_point.set_v(point.second);
    st_graph_debug->add_speed_limit()->CopyFrom(speed_point);
  }
}
}  // namespace planning
}  // namespace apollo
<commit_msg>Update speed_bounds_decider.cc<commit_after>/******************************************************************************
 * Copyright 2019 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/planning/tasks/deciders/speed_bounds_decider/speed_bounds_decider.h"

#include <string>
#include <tuple>
#include <vector>

#include "modules/common/vehicle_state/vehicle_state_provider.h"
#include "modules/planning/common/change_lane_decider.h"
#include "modules/planning/common/path/path_data.h"
#include "modules/planning/common/planning_context.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/common/st_graph_data.h"
#include "modules/planning/tasks/deciders/decider_rule_based_stop.h"
#include "modules/planning/tasks/deciders/speed_bounds_decider/speed_limit_decider.h"
#include "modules/planning/tasks/deciders/speed_bounds_decider/st_boundary_mapper.h"

namespace apollo {
namespace planning {

using apollo::common::ErrorCode;
using apollo::common::SLPoint;
using apollo::common::Status;
using apollo::common::TrajectoryPoint;
using apollo::planning_internal::StGraphBoundaryDebug;
using apollo::planning_internal::STGraphDebug;

SpeedBoundsDecider::SpeedBoundsDecider(const TaskConfig &config)
    : Decider(config) {
  CHECK(config.has_speed_bounds_decider_config());
  speed_bounds_config_ = config.speed_bounds_decider_config();
  SetName("SpeedBoundsDecider");
}

Status SpeedBoundsDecider::Process(
    Frame *const frame, ReferenceLineInfo *const reference_line_info) {
  // retrieve data from frame and reference_line_info
  const SLBoundary &adc_sl_boundary = reference_line_info->AdcSlBoundary();
  const PathData &path_data = reference_line_info->path_data();
  const TrajectoryPoint &init_point = frame->PlanningStartPoint();
  const ReferenceLine &reference_line = reference_line_info->reference_line();
  PathDecision *const path_decision = reference_line_info->path_decision();

  // 1. Rule_based speed planning configurations for different traffic scenarios
  if (FLAGS_enable_nonscenario_side_pass) {
    double stop_s_on_pathdata = 0.0;
    bool set_stop_fence = false;
    const auto &side_pass_info = PlanningContext::side_pass_info();
    auto *mutable_side_pass_info = PlanningContext::mutable_side_pass_info();
    if (side_pass_info.change_lane_stop_flag) {
      // Check if stop at last frame stop fence
      if (CheckADCStop(*reference_line_info,
                       side_pass_info.change_lane_stop_path_point)) {
        if (ChangeLaneDecider::IsClearToChangeLane(reference_line_info)) {
          mutable_side_pass_info->check_clear_flag = true;
        } else if (CheckSidePassStop(path_data, &stop_s_on_pathdata)) {
          set_stop_fence = BuildSidePassStopFence(
              path_data, stop_s_on_pathdata,
              &(mutable_side_pass_info->change_lane_stop_path_point), frame,
              reference_line_info);
        }

      } else {
        if (CheckSidePassStop(path_data, &stop_s_on_pathdata)) {
          set_stop_fence = BuildSidePassStopFence(
              path_data, stop_s_on_pathdata,
              &(mutable_side_pass_info->change_lane_stop_path_point), frame,
              reference_line_info);
        }
      }
    } else {
      if (!side_pass_info.check_clear_flag &&
          CheckSidePassStop(path_data, &stop_s_on_pathdata)) {
        set_stop_fence = BuildSidePassStopFence(
            path_data, stop_s_on_pathdata,
            &(mutable_side_pass_info->change_lane_stop_path_point), frame,
            reference_line_info);
      }
      if (side_pass_info.check_clear_flag &&
          CheckClearDone(*reference_line_info,
                         side_pass_info.change_lane_stop_path_point)) {
        mutable_side_pass_info->check_clear_flag = false;
      }
    }
    mutable_side_pass_info->change_lane_stop_flag = set_stop_fence;
  }

  // 2. Map obstacles into st graph
  StBoundaryMapper boundary_mapper(adc_sl_boundary, speed_bounds_config_,
                                   reference_line, path_data,
                                   speed_bounds_config_.total_path_length(),
                                   speed_bounds_config_.total_time(),
                                   reference_line_info_->IsChangeLanePath());

  path_decision->EraseStBoundaries();
  if (boundary_mapper.CreateStBoundary(path_decision).code() ==
      ErrorCode::PLANNING_ERROR) {
    const std::string msg = "Mapping obstacle failed.";
    AERROR << msg;
    return Status(ErrorCode::PLANNING_ERROR, msg);
  }

  std::vector<const STBoundary *> boundaries;
  for (auto *obstacle : path_decision->obstacles().Items()) {
    auto id = obstacle->Id();
    if (!obstacle->st_boundary().IsEmpty()) {
      if (obstacle->st_boundary().boundary_type() ==
          STBoundary::BoundaryType::KEEP_CLEAR) {
        path_decision->Find(id)->SetBlockingObstacle(false);
      } else {
        path_decision->Find(id)->SetBlockingObstacle(true);
      }
      boundaries.push_back(&obstacle->st_boundary());
    }
  }

  // 3. Create speed limit along path
  SpeedLimitDecider speed_limit_decider(adc_sl_boundary, speed_bounds_config_,
                                        reference_line, path_data);

  SpeedLimit speed_limit;
  if (!speed_limit_decider
           .GetSpeedLimits(path_decision->obstacles(), &speed_limit)
           .ok()) {
    std::string msg("Getting speed limits failed!");
    AERROR << msg;
    return Status(ErrorCode::PLANNING_ERROR, msg);
  }

  // 3. Get path_length as s axis search bound in st graph
  const double path_data_length = path_data.discretized_path().Length();
  const double path_length_by_conf = speed_bounds_config_.total_path_length();

  // 4. Get time duration as t axis search bound in st graph
  const double total_time_by_conf = speed_bounds_config_.total_time();

  // Load generated st graph data back to frame
  StGraphData *st_graph_data = reference_line_info_->mutable_st_graph_data();

  // Add a st_graph debug info and save the pointer to st_graph_data for
  // optimizer logging
  auto *debug = reference_line_info_->mutable_debug();
  STGraphDebug *st_graph_debug = debug->mutable_planning_data()->add_st_graph();

  st_graph_data->LoadData(boundaries, init_point, speed_limit, path_data_length,
                          path_length_by_conf, total_time_by_conf,
                          st_graph_debug);

  // Create and record st_graph debug info
  RecordSTGraphDebug(*st_graph_data, st_graph_debug);

  return Status::OK();
}

// @brief Check if necessary to set stop fence used for nonscenario side pass
bool SpeedBoundsDecider::CheckSidePassStop(const PathData &path_data,
                                           double *stop_s_on_pathdata) {
  const std::vector<std::tuple<double, PathData::PathPointType, double>>
      &path_point_decision_guide = path_data.path_point_decision_guide();
  PathData::PathPointType last_path_point_type =
      PathData::PathPointType::UNKNOWN;
  for (const auto &point_guide : path_point_decision_guide) {
    if (last_path_point_type == PathData::PathPointType::IN_LANE &&
        std::get<1>(point_guide) != PathData::PathPointType::IN_LANE) {
      *stop_s_on_pathdata = std::get<0>(point_guide);
      return true;
    }
    last_path_point_type = std::get<1>(point_guide);
  }
  return false;
}

// @brief Set stop fence for side pass
bool SpeedBoundsDecider::BuildSidePassStopFence(
    const PathData &path_data, const double stop_s_on_pathdata,
    common::PathPoint *stop_pathpoint, Frame *const frame,
    ReferenceLineInfo *const reference_line_info) {
  CHECK_NOTNULL(frame);
  CHECK_NOTNULL(reference_line_info);

  if (!path_data.GetPathPointWithRefS(stop_s_on_pathdata, stop_pathpoint)) {
    return false;
  }

  const std::string stop_wall_id = "side_pass_stop";
  // TODO(Jinyun) load relavent surrounding obstacles
  std::vector<std::string> wait_for_obstacles;

  const auto &nearby_path = reference_line_info->reference_line().map_path();
  double stop_point_s = 0.0;
  double stop_point_l = 0.0;
  nearby_path.GetNearestPoint({stop_pathpoint->x(), stop_pathpoint->y()},
                              &stop_point_s, &stop_point_l);

  DeciderRuleBasedStop::BuildStopDecision(
      stop_wall_id, stop_point_s, 0.0,
      StopReasonCode::STOP_REASON_SIDEPASS_SAFETY, wait_for_obstacles, frame,
      reference_line_info);

  return true;
}

// @brief Check if ADV stop at a stop fence
bool SpeedBoundsDecider::CheckADCStop(
    const ReferenceLineInfo &reference_line_info,
    const common::PathPoint &stop_point) {
  const double adc_speed =
      common::VehicleStateProvider::Instance()->linear_velocity();
  if (adc_speed > speed_bounds_config_.max_adc_stop_speed()) {
    ADEBUG << "ADC not stopped: speed[" << adc_speed << "]";
    return false;
  }

  // check stop close enough to stop line of the stop_sign
  const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s();
  const auto &nearby_path = reference_line_info.reference_line().map_path();
  double stop_point_s = 0.0;
  double stop_point_l = 0.0;
  nearby_path.GetNearestPoint({stop_point.x(), stop_point.y()}, &stop_point_s,
                              &stop_point_l);

  const double distance_stop_line_to_adc_front_edge =
      stop_point_s - adc_front_edge_s;

  if (distance_stop_line_to_adc_front_edge >
      speed_bounds_config_.max_valid_stop_distance()) {
    ADEBUG << "not a valid stop. too far from stop line.";
    return false;
  }

  return true;
}

bool SpeedBoundsDecider::CheckClearDone(
    const ReferenceLineInfo &reference_line_info,
    const common::PathPoint &stop_point) {
  const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s();
  const double adc_back_edge_s = reference_line_info.AdcSlBoundary().start_s();
  const double adc_start_l = reference_line_info.AdcSlBoundary().start_l();
  const double adc_end_l = reference_line_info.AdcSlBoundary().end_l();
  double lane_left_width = 0.0;
  double lane_right_width = 0.0;
  reference_line_info.reference_line().GetLaneWidth(
      (adc_front_edge_s + adc_back_edge_s) / 2.0, &lane_left_width,
      &lane_right_width);
  SLPoint stop_sl_point;
  reference_line_info.reference_line().XYToSL({stop_point.x(), stop_point.y()},
                                              &stop_sl_point);
  // use distance to last stop point to determine if needed to check clear again
  if (adc_back_edge_s > stop_sl_point.s()) {
    if (adc_start_l > -lane_right_width || adc_end_l < lane_left_width) {
      return true;
    }
  }
  return false;
}

void SpeedBoundsDecider::RecordSTGraphDebug(
    const StGraphData &st_graph_data, STGraphDebug *st_graph_debug) const {
  if (!FLAGS_enable_record_debug || !st_graph_debug) {
    ADEBUG << "Skip record debug info";
    return;
  }

  for (const auto &boundary : st_graph_data.st_boundaries()) {
    auto boundary_debug = st_graph_debug->add_boundary();
    boundary_debug->set_name(boundary->id());
    switch (boundary->boundary_type()) {
      case STBoundary::BoundaryType::FOLLOW:
        boundary_debug->set_type(StGraphBoundaryDebug::ST_BOUNDARY_TYPE_FOLLOW);
        break;
      case STBoundary::BoundaryType::OVERTAKE:
        boundary_debug->set_type(
            StGraphBoundaryDebug::ST_BOUNDARY_TYPE_OVERTAKE);
        break;
      case STBoundary::BoundaryType::STOP:
        boundary_debug->set_type(StGraphBoundaryDebug::ST_BOUNDARY_TYPE_STOP);
        break;
      case STBoundary::BoundaryType::UNKNOWN:
        boundary_debug->set_type(
            StGraphBoundaryDebug::ST_BOUNDARY_TYPE_UNKNOWN);
        break;
      case STBoundary::BoundaryType::YIELD:
        boundary_debug->set_type(StGraphBoundaryDebug::ST_BOUNDARY_TYPE_YIELD);
        break;
      case STBoundary::BoundaryType::KEEP_CLEAR:
        boundary_debug->set_type(
            StGraphBoundaryDebug::ST_BOUNDARY_TYPE_KEEP_CLEAR);
        break;
    }

    for (const auto &point : boundary->points()) {
      auto point_debug = boundary_debug->add_point();
      point_debug->set_t(point.x());
      point_debug->set_s(point.y());
    }
  }

  for (const auto &point : st_graph_data.speed_limit().speed_limit_points()) {
    common::SpeedPoint speed_point;
    speed_point.set_s(point.first);
    speed_point.set_v(point.second);
    st_graph_debug->add_speed_limit()->CopyFrom(speed_point);
  }
}
}  // namespace planning
}  // namespace apollo
<|endoftext|>


<commit_before>
#undef NDEBUG
#include "benchmark/benchmark.h"
#include "../src/check.h" // NOTE: check.h is for internal use only!
#include <cassert>
#include <vector>

namespace {

class TestReporter : public benchmark::ConsoleReporter {
public:
  virtual void ReportRuns(const std::vector<Run>& report) {
    all_runs_.insert(all_runs_.end(), begin(report), end(report));
    ConsoleReporter::ReportRuns(report);
  }

  std::vector<Run> all_runs_;
};

struct TestCase {
  std::string name;
  const char* label;
  TestCase(const char* xname) : name(xname), label(nullptr) {}
  TestCase(const char* xname, const char* xlabel)
    : name(xname), label(xlabel) {}

  typedef benchmark::BenchmarkReporter::Run Run;

  void CheckRun(Run const& run) const {
    CHECK(name == run.benchmark_name) << "expected " << name
                                      << " got " << run.benchmark_name;
    if (label) {
      CHECK(run.report_label == label) << "expected " << label
                                       << " got " << run.report_label;
    } else {
      CHECK(run.report_label == "");
    }
  }
};

std::vector<TestCase> ExpectedResults;

int AddCases(std::initializer_list<TestCase> const& v) {
  for (auto N : v) {
    ExpectedResults.push_back(N);
  }
  return 0;
}

#define CONCAT(x, y) CONCAT2(x, y)
#define CONCAT2(x, y) x##y
#define ADD_CASES(...) \
int CONCAT(dummy, __LINE__) = AddCases({__VA_ARGS__})

}  // end namespace

typedef benchmark::internal::Benchmark* ReturnVal;

//----------------------------------------------------------------------------//
// Test RegisterBenchmark with no additional arguments
//----------------------------------------------------------------------------//
void BM_function(benchmark::State& state) { while (state.KeepRunning()) {} }
BENCHMARK(BM_function);
ReturnVal dummy = benchmark::RegisterBenchmark(
    "BM_function_manual_registration",
     BM_function);
ADD_CASES({"BM_function"}, {"BM_function_manual_registration"});

//----------------------------------------------------------------------------//
// Test RegisterBenchmark with additional arguments
// Note: GCC <= 4.8 do not support this form of RegisterBenchmark because they
//       reject the variadic pack expansion of lambda captures.
//----------------------------------------------------------------------------//
#ifndef BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK

void BM_extra_args(benchmark::State& st, const char* label) {
  while (st.KeepRunning()) {}
  st.SetLabel(label);
}
int RegisterFromFunction() {
  std::pair<const char*, const char*> cases[] = {
      {"test1", "One"},
      {"test2", "Two"},
      {"test3", "Three"}
  };
  for (auto& c : cases)
    benchmark::RegisterBenchmark(c.first, &BM_extra_args, c.second);
  return 0;
}
int dummy2 = RegisterFromFunction();
ADD_CASES(
  {"test1", "One"},
  {"test2", "Two"},
  {"test3", "Three"}
);

#endif // BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK

//----------------------------------------------------------------------------//
// Test RegisterBenchmark with different callable types
//----------------------------------------------------------------------------//

struct CustomFixture {
  void operator()(benchmark::State& st) {
    while (st.KeepRunning()) {}
  }
};

void TestRegistrationAtRuntime() {
  {
    CustomFixture fx;
    benchmark::RegisterBenchmark("custom_fixture", fx);
    AddCases({"custom_fixture"});
  }
#ifndef BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK
  {
    int x = 42;
    auto capturing_lam = [=](benchmark::State& st) {
      while (st.KeepRunning()) {}
      st.SetLabel(std::to_string(x));
    };
    benchmark::RegisterBenchmark("lambda_benchmark", capturing_lam);
    AddCases({{"lambda_benchmark", "42"}});
  }
#endif
}

int main(int argc, char* argv[]) {
  TestRegistrationAtRuntime();

  benchmark::Initialize(&argc, argv);

  TestReporter test_reporter;
  benchmark::RunSpecifiedBenchmarks(&test_reporter);

  typedef benchmark::BenchmarkReporter::Run Run;
  auto EB = ExpectedResults.begin();

  for (Run const& run : test_reporter.all_runs_) {
    assert(EB != ExpectedResults.end());
    EB->CheckRun(run);
    ++EB;
  }
  assert(EB == ExpectedResults.end());

  return 0;
}
<commit_msg>Hide yet another test from MSVC 2013<commit_after>
#undef NDEBUG
#include "benchmark/benchmark.h"
#include "../src/check.h" // NOTE: check.h is for internal use only!
#include <cassert>
#include <vector>

namespace {

class TestReporter : public benchmark::ConsoleReporter {
public:
  virtual void ReportRuns(const std::vector<Run>& report) {
    all_runs_.insert(all_runs_.end(), begin(report), end(report));
    ConsoleReporter::ReportRuns(report);
  }

  std::vector<Run> all_runs_;
};

struct TestCase {
  std::string name;
  const char* label;
  TestCase(const char* xname) : name(xname), label(nullptr) {}
  TestCase(const char* xname, const char* xlabel)
    : name(xname), label(xlabel) {}

  typedef benchmark::BenchmarkReporter::Run Run;

  void CheckRun(Run const& run) const {
    CHECK(name == run.benchmark_name) << "expected " << name
                                      << " got " << run.benchmark_name;
    if (label) {
      CHECK(run.report_label == label) << "expected " << label
                                       << " got " << run.report_label;
    } else {
      CHECK(run.report_label == "");
    }
  }
};

std::vector<TestCase> ExpectedResults;

int AddCases(std::initializer_list<TestCase> const& v) {
  for (auto N : v) {
    ExpectedResults.push_back(N);
  }
  return 0;
}

#define CONCAT(x, y) CONCAT2(x, y)
#define CONCAT2(x, y) x##y
#define ADD_CASES(...) \
int CONCAT(dummy, __LINE__) = AddCases({__VA_ARGS__})

}  // end namespace

typedef benchmark::internal::Benchmark* ReturnVal;

//----------------------------------------------------------------------------//
// Test RegisterBenchmark with no additional arguments
//----------------------------------------------------------------------------//
void BM_function(benchmark::State& state) { while (state.KeepRunning()) {} }
BENCHMARK(BM_function);
ReturnVal dummy = benchmark::RegisterBenchmark(
    "BM_function_manual_registration",
     BM_function);
ADD_CASES({"BM_function"}, {"BM_function_manual_registration"});

//----------------------------------------------------------------------------//
// Test RegisterBenchmark with additional arguments
// Note: GCC <= 4.8 do not support this form of RegisterBenchmark because they
//       reject the variadic pack expansion of lambda captures.
//----------------------------------------------------------------------------//
#ifndef BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK

void BM_extra_args(benchmark::State& st, const char* label) {
  while (st.KeepRunning()) {}
  st.SetLabel(label);
}
int RegisterFromFunction() {
  std::pair<const char*, const char*> cases[] = {
      {"test1", "One"},
      {"test2", "Two"},
      {"test3", "Three"}
  };
  for (auto& c : cases)
    benchmark::RegisterBenchmark(c.first, &BM_extra_args, c.second);
  return 0;
}
int dummy2 = RegisterFromFunction();
ADD_CASES(
  {"test1", "One"},
  {"test2", "Two"},
  {"test3", "Three"}
);

#endif // BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK

//----------------------------------------------------------------------------//
// Test RegisterBenchmark with different callable types
//----------------------------------------------------------------------------//

struct CustomFixture {
  void operator()(benchmark::State& st) {
    while (st.KeepRunning()) {}
  }
};

void TestRegistrationAtRuntime() {
#ifdef BENCHMARK_HAS_CXX11
  {
    CustomFixture fx;
    benchmark::RegisterBenchmark("custom_fixture", fx);
    AddCases({"custom_fixture"});
  }
#endif
#ifndef BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK
  {
    int x = 42;
    auto capturing_lam = [=](benchmark::State& st) {
      while (st.KeepRunning()) {}
      st.SetLabel(std::to_string(x));
    };
    benchmark::RegisterBenchmark("lambda_benchmark", capturing_lam);
    AddCases({{"lambda_benchmark", "42"}});
  }
#endif
}

int main(int argc, char* argv[]) {
  TestRegistrationAtRuntime();

  benchmark::Initialize(&argc, argv);

  TestReporter test_reporter;
  benchmark::RunSpecifiedBenchmarks(&test_reporter);

  typedef benchmark::BenchmarkReporter::Run Run;
  auto EB = ExpectedResults.begin();

  for (Run const& run : test_reporter.all_runs_) {
    assert(EB != ExpectedResults.end());
    EB->CheckRun(run);
    ++EB;
  }
  assert(EB == ExpectedResults.end());

  return 0;
}
<|endoftext|>


<commit_before>#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW
#endif

#include "Entity.h"
#include <Texture.h>
#include <Renderer2D.h>
#include "TextureManager.h"
#include "Level.h"
#include "Map.h"
#include "Tile.h"

const unsigned int Entity::m_defaultColor = (255 << 24) + (255 << 16) + (255 << 8) + 255;

Entity::Entity(Level* _level, EntityID _id, EntityTeam _team)
	: m_level(_level), m_id(_id), m_team(_team), m_x(), m_y(), m_dir(0), m_color(m_defaultColor), m_progress(0), m_speed(1), m_turn(0), m_active(false)
{
}

Entity::~Entity()
{
}

void Entity::Draw(aie::Renderer2D * _renderer)
{
	if (!m_active) { return; }

	float newX, newY;
	m_level->m_map->TileToWorld(m_x, m_y, newX, newY);
	float width = m_level->m_map->GetTileWidth();
	float height = m_level->m_map->GetTileHeight();

	_renderer->setRenderColour(m_color);
	_renderer->drawSprite(m_texture, newX + width * 0.5f, newY + height * 0.5f, width, height, (m_dir * 3.1415926535897) / 180.0f);
	_renderer->setRenderColour(m_defaultColor);
}

void Entity::UpdateMovement(float _deltaTime)
{
	TryCollision();
	UpdateProgress(_deltaTime);
}

void Entity::UpdateProgress(float _deltaTime)
{
	m_progress += _deltaTime * m_speed;
	while (m_progress > 1)
	{
		m_progress -= 1;

		CalcMovement();

		TryCollision();
	}
}

void Entity::CalcMovement()
{
	//if (TryMoveInDir(DirWrap(m_dir))) {}
	//else if (TryMoveInDir(DirWrap(m_dir - 90))) {} // Move Left
	//else if (TryMoveInDir(DirWrap(m_dir + 90))) {} // Move Right

	if (TryMoveInDir(GetTurnedDir())) {} // Move Turn Dir
	else if (TryMoveInDir(DirWrap(m_dir))) {} // Move Forewards
	else if (TryMoveInDir(DirWrap(m_dir + 90))) {} // Move Left
	else if (TryMoveInDir(DirWrap(m_dir - 90))) {} // Move Right
	else TryMoveInDir(DirWrap(m_dir + 180)); {} // Move Backwards
}

void Entity::CheckCollision(Entity* a_entity)
{
	if (a_entity->m_x == m_x && a_entity->m_y == m_y)
		OnCollision(a_entity);
}

void Entity::TryCollision()
{
	for (auto i = m_level->m_entities.begin(); i != m_level->m_entities.end(); i++)
	{
		if ((*i)->m_team != m_team && (*i)->m_active)
			CheckCollision((*i));
	}
}

// Clamps m_dir to 0-359 spectrum
void Entity::DirWrap()
{
	m_dir = DirWrap(m_dir);
}

// Clamps Dir to 0-359 spectrum
int Entity::DirWrap(int _dir) const
{
	while (_dir >= 360) _dir -= 360;
	while (_dir < 0) _dir += 360;
	return _dir;
}

// Expects m_dir to be in 90 increments and clamped to 0-359
void Entity::DirToXYOffset(int & _outX, int & _outY)
{
	DirToXYOffset(m_dir, _outX, _outY);
}

// Expects _dir to be in 90 increments and clamped to 0-359
void Entity::DirToXYOffset(int & _dir, int & _outX, int & _outY) const
{
	switch (_dir)
	{
	case 0:
		_outX = 1; _outY = 0;
		break;
	case 90:
		_outX = 0; _outY = -1;
		break;
	case 180:
		_outX = -1; _outY = 0;
		break;
	case 270:
		_outX = 0; _outY = 1;
		break;
	default:
		_outX = 0; _outY = 0;
		break;
	}
}

unsigned int Entity::CToIColor(const char & a, const char & r, const char & g, const char & b)
{
	return ((b & 0xFF) << 24) | //alpha
		(((int)g & 0xFF) << 16) | //red
		(((int)r & 0xFF) << 8) | //green
		(((int)a & 0xFF) << 0); //blue
}

int Entity::GetTileColID(int _x, int _y) const
{
	int width = m_level->m_map->GetWidth();
	int height = m_level->m_map->GetDepth();
	if (_x >= width) _x = width - 1;
	if (_y >= height) _y = height - 1;
	return m_level->m_map->GetTile(0, _x, _y).GetTileID();
}

int Entity::GetTileColIDByDir(const int & _dir) const
{
	int dir = DirWrap(_dir);

	int dirX, dirY;
	DirToXYOffset(dir, dirX, dirY);

	int frontX = m_x + dirX;
	int frontY = m_y + dirY;
	return GetTileColID(frontX, frontY);
}

bool Entity::TryMoveInDir(const int & _dir)
{
	int tryDir = DirWrap(_dir);
	int tryID = GetTileColIDByDir(tryDir);

	if (!(tryID != 0))
	{ // Empty space, so move
		int xOS, yOS;
		m_dir = tryDir;
		DirToXYOffset(tryDir, xOS, yOS);
		m_x += xOS; m_y += yOS;
		return true;
	}
	else return false;
}

int Entity::GetTurnedDir() const
{
	int newDir = m_dir;
	switch (m_turn)
	{
	case -1:
		newDir -= 90;
		break;
	case 0:
		break;
	case 1:
		newDir += 90;
		break;
	default:
		break;
	}
	return DirWrap(newDir);
}
<commit_msg>Fixed Movement<commit_after>#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW
#endif

#include "Entity.h"
#include <Texture.h>
#include <Renderer2D.h>
#include "TextureManager.h"
#include "Level.h"
#include "Map.h"
#include "Tile.h"

const unsigned int Entity::m_defaultColor = (255 << 24) + (255 << 16) + (255 << 8) + 255;

Entity::Entity(Level* _level, EntityID _id, EntityTeam _team)
	: m_level(_level), m_id(_id), m_team(_team), m_x(), m_y(), m_dir(0), m_color(m_defaultColor), m_progress(0), m_speed(1), m_turn(0), m_active(false)
{
}

Entity::~Entity()
{
}

void Entity::Draw(aie::Renderer2D * _renderer)
{
	if (!m_active) { return; }

	float newX, newY;
	m_level->m_map->TileToWorld(m_x, m_y, newX, newY);
	float width = m_level->m_map->GetTileWidth();
	float height = m_level->m_map->GetTileHeight();

	_renderer->setRenderColour(m_color);
	_renderer->drawSprite(m_texture, newX + width * 0.5f, newY + height * 0.5f, width, height, (m_dir * 3.1415926535897) / 180.0f);
	_renderer->setRenderColour(m_defaultColor);
}

void Entity::UpdateMovement(float _deltaTime)
{
	TryCollision();
	UpdateProgress(_deltaTime);
}

void Entity::UpdateProgress(float _deltaTime)
{
	m_progress += _deltaTime * m_speed;
	while (m_progress > 1)
	{
		m_progress -= 1;

		CalcMovement();

		TryCollision();
	}
}

void Entity::CalcMovement()
{
	if		(TryMoveInDir(		GetTurnedDir())) {}		// Move Turn Dir
	else if (TryMoveInDir(	DirWrap(m_dir))) {}			// Move Forewards
	else if (TryMoveInDir(	DirWrap(m_dir - 90))) {}	// Turn Move
	else if (TryMoveInDir(	DirWrap(m_dir + 90))) {}	// Turn Move
	else	TryMoveInDir(		DirWrap(m_dir + 180)); {} // Move Backwards
}

void Entity::CheckCollision(Entity* a_entity)
{
	if (a_entity->m_x == m_x && a_entity->m_y == m_y)
		OnCollision(a_entity);
}

void Entity::TryCollision()
{
	for (auto i = m_level->m_entities.begin(); i != m_level->m_entities.end(); i++)
	{
		if ((*i)->m_team != m_team && (*i)->m_active)
			CheckCollision((*i));
	}
}

// Clamps m_dir to 0-359 spectrum
void Entity::DirWrap()
{
	m_dir = DirWrap(m_dir);
}

// Clamps Dir to 0-359 spectrum
int Entity::DirWrap(int _dir) const
{
	while (_dir >= 360) _dir -= 360;
	while (_dir < 0) _dir += 360;
	return _dir;
}

// Expects m_dir to be in 90 increments and clamped to 0-359
void Entity::DirToXYOffset(int & _outX, int & _outY)
{
	DirToXYOffset(m_dir, _outX, _outY);
}

// Expects _dir to be in 90 increments and clamped to 0-359
void Entity::DirToXYOffset(int & _dir, int & _outX, int & _outY) const
{
	switch (_dir)
	{
	case 0:
		_outX = 1; _outY = 0;
		break;
	case 90:
		_outX = 0; _outY = 1;
		break;
	case 180:
		_outX = -1; _outY = 0;
		break;
	case 270:
		_outX = 0; _outY = -1;
		break;
	default:
		_outX = 0; _outY = 0;
		break;
	}
}

unsigned int Entity::CToIColor(const char & a, const char & r, const char & g, const char & b)
{
	return ((b & 0xFF) << 24) | //alpha
		(((int)g & 0xFF) << 16) | //red
		(((int)r & 0xFF) << 8) | //green
		(((int)a & 0xFF) << 0); //blue
}

int Entity::GetTileColID(int _x, int _y) const
{
	int width = m_level->m_map->GetWidth();
	int height = m_level->m_map->GetDepth();
	if (_x >= width) _x = width - 1;
	if (_y >= height) _y = height - 1;
	return m_level->m_map->GetTile(0, _x, _y).GetTileID();
}

int Entity::GetTileColIDByDir(const int & _dir) const
{
	int dir = DirWrap(_dir);

	int dirX, dirY;
	DirToXYOffset(dir, dirX, dirY);

	int frontX = m_x + dirX;
	int frontY = m_y + dirY;
	return GetTileColID(frontX, frontY);
}

bool Entity::TryMoveInDir(const int & _dir)
{
	int tryDir = DirWrap(_dir);

	int xOS, yOS;
	DirToXYOffset(tryDir, xOS, yOS);
	xOS = m_x + xOS;
	yOS = m_y + yOS;
	int tryID = GetTileColID(xOS, yOS);//GetTileColIDByDir(tryDir);

	if (tryID != 0)
		return false;
	else {
		// Empty space, so move
		m_dir = tryDir;
		m_x = xOS; m_y = yOS;
		return true;
	}
}

int Entity::GetTurnedDir() const
{
	int newDir = m_dir;
	switch (m_turn)
	{
	case -1:
		newDir -= 90;
		break;
	case 0:
		break;
	case 1:
		newDir += 90;
		break;
	default:
		break;
	}
	return DirWrap(newDir);
}
<|endoftext|>


<commit_before>#include "LocalItemManager.h"
#include "ItemContainer.h"
#include <document-manager/DocumentManager.h>
#include <document-manager/Document.h>

namespace sf1r
{

LocalItemManager::LocalItemManager(DocumentManager& docManager)
    : docManager_(docManager)
{
}

bool LocalItemManager::hasItem(itemid_t itemId)
{
    return itemId <= docManager_.getMaxDocId() &&
           !docManager_.isDeleted(itemId);
}

bool LocalItemManager::getItemProps(
    const std::vector<std::string>& propList,
    ItemContainer& itemContainer
)
{
    bool result = true;
    const std::size_t itemNum = itemContainer.getItemNum();

    for (std::size_t i = 0; i < itemNum; ++i)
    {
        Document& doc = itemContainer.getItem(i);
        doc.clearProperties();

        if (! docManager_.getDocument(doc.getId(), doc))
            result = false;
    }

    return result;
}

} // namespace sf1r
<commit_msg>in 11ef0bf86797b930ddfb72059f6df0ace3bfef1d, it revised DocumentManager::getDocument() not to return RType property values.<commit_after>#include "LocalItemManager.h"
#include "ItemContainer.h"
#include <document-manager/DocumentManager.h>
#include <document-manager/Document.h>

namespace sf1r
{

LocalItemManager::LocalItemManager(DocumentManager& docManager)
    : docManager_(docManager)
{
}

bool LocalItemManager::hasItem(itemid_t itemId)
{
    return itemId <= docManager_.getMaxDocId() &&
           !docManager_.isDeleted(itemId);
}

bool LocalItemManager::getItemProps(
    const std::vector<std::string>& propList,
    ItemContainer& itemContainer
)
{
    bool result = true;
    const std::size_t itemNum = itemContainer.getItemNum();

    for (std::size_t i = 0; i < itemNum; ++i)
    {
        Document& doc = itemContainer.getItem(i);
        doc.clearProperties();
        docid_t docId = doc.getId();

        if (docManager_.getDocument(docId, doc))
        {
            docManager_.getRTypePropertiesForDocument(docId, doc);
        }
        else
        {
            result = false;
        }
    }

    return result;
}

} // namespace sf1r
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <algorithm>
#include <iterator>
#include <iv/alloc.h>
#include <iv/ustring.h>
#include <iv/stringpiece.h>
#include <iv/conversions.h>
#include <iv/aero/aero.h>
#include "test_aero.h"
namespace {

template<typename T>
bool ExpectEqual(T reg,
                 const iv::core::StringPiece& expected) {
  const iv::core::UString r = iv::core::ToUString(reg);
  iv::core::UString res;
  iv::core::RegExpEscape(r.begin(), r.end(), std::back_inserter(res));
  return res == iv::core::ToUString(expected);
}

}  // namespace anonymous

TEST(AeroSourceEscapeCase, SlashInBrackTest) {
  EXPECT_TRUE(ExpectEqual("[/]", "[/]")) << "[/] => [/]";
  EXPECT_TRUE(ExpectEqual("[\\]/]", "[\\]/]")) << "[\\]/] => [\\]/]";
}

TEST(AeroSourceEscapeCase, SlashTest) {
  EXPECT_TRUE(ExpectEqual("/", "\\/")) << "/ => \\/";
  EXPECT_TRUE(ExpectEqual("\\/", "\\/")) << "\\/ => \\/";
}

TEST(AeroSourceEscapeCase, LineTerminatorTest) {
  EXPECT_TRUE(ExpectEqual("\n", "\\n")) << "\\n => \\n";
  EXPECT_TRUE(ExpectEqual("\\\n", "\\\\n")) << "\\\\n => \\\\n";
  EXPECT_TRUE(ExpectEqual(0x2028, "\\u2028")) << "2028 code => \\u2028";
  EXPECT_TRUE(ExpectEqual(0x2029, "\\u2029")) << "2029 code => \\u2029";
}

TEST(AeroSourceEscapeCase, OneCharTest) {
  iv::core::Space space;
  for (uint32_t ch = 0; ch <= 0xFFFF; ++ch) {
    iv::core::UString str = iv::core::ToUString(ch);
    {
      space.Clear();
      iv::aero::Parser parser(&space, str, iv::aero::NONE);
      int error = 0;
      parser.ParsePattern(&error);
      if (error) {  // invalid, like '['
        continue;
      }
    }
    iv::core::UString res;
    iv::core::RegExpEscape(str.begin(), str.end(), std::back_inserter(res));
    {
      space.Clear();
      iv::aero::Parser parser(&space, str, iv::aero::NONE);
      int error = 0;
      iv::aero::ParsedData data = parser.ParsePattern(&error);
      EXPECT_FALSE(error);
    }
  }
}
<commit_msg>add SpecialCharactersTest in aero escape #38<commit_after>#include <gtest/gtest.h>
#include <algorithm>
#include <iterator>
#include <iv/alloc.h>
#include <iv/ustring.h>
#include <iv/stringpiece.h>
#include <iv/conversions.h>
#include <iv/aero/aero.h>
#include "test_aero.h"
namespace {

template<typename T>
bool ExpectEqual(T reg,
                 const iv::core::StringPiece& expected) {
  const iv::core::UString r = iv::core::ToUString(reg);
  iv::core::UString res;
  iv::core::RegExpEscape(r.begin(), r.end(), std::back_inserter(res));
  return res == iv::core::ToUString(expected);
}

}  // namespace anonymous

TEST(AeroSourceEscapeCase, SlashInBrackTest) {
  EXPECT_TRUE(ExpectEqual("[/]", "[/]")) << "[/] => [/]";
  EXPECT_TRUE(ExpectEqual("[\\]/]", "[\\]/]")) << "[\\]/] => [\\]/]";
}

TEST(AeroSourceEscapeCase, SlashTest) {
  EXPECT_TRUE(ExpectEqual("/", "\\/")) << "/ => \\/";
  EXPECT_TRUE(ExpectEqual("\\/", "\\/")) << "\\/ => \\/";
}

TEST(AeroSourceEscapeCase, LineTerminatorTest) {
  EXPECT_TRUE(ExpectEqual("\n", "\\n")) << "\\n => \\n";
  EXPECT_TRUE(ExpectEqual("\\\n", "\\\\n")) << "\\\\n => \\\\n";
  EXPECT_TRUE(ExpectEqual(0x2028, "\\u2028")) << "2028 code => \\u2028";
  EXPECT_TRUE(ExpectEqual(0x2029, "\\u2029")) << "2029 code => \\u2029";
}

TEST(AeroSourceEscapeCase, SpecialCharactersTest) {
  EXPECT_TRUE(ExpectEqual("^$\\.*+?()[]{}|", "^$\\.*+?()[]{}|"));
}

TEST(AeroSourceEscapeCase, OneCharTest) {
  iv::core::Space space;
  for (uint32_t ch = 0; ch <= 0xFFFF; ++ch) {
    iv::core::UString str = iv::core::ToUString(ch);
    {
      space.Clear();
      iv::aero::Parser parser(&space, str, iv::aero::NONE);
      int error = 0;
      parser.ParsePattern(&error);
      if (error) {  // invalid, like '['
        continue;
      }
    }
    iv::core::UString res;
    iv::core::RegExpEscape(str.begin(), str.end(), std::back_inserter(res));
    {
      space.Clear();
      iv::aero::Parser parser(&space, str, iv::aero::NONE);
      int error = 0;
      iv::aero::ParsedData data = parser.ParsePattern(&error);
      EXPECT_FALSE(error);
    }
  }
}
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                        Intel License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of Intel Corporation may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "precomp.hpp"

// temporarily remove it from build
#if 0 && ((_MSC_VER>=1200) || defined __BORLANDC__)

double CvMAT::get( const uchar* ptr, int type, int coi )
{
    double t = 0;
    assert( (unsigned)coi < (unsigned)CV_MAT_CN(type) );

    switch( CV_MAT_DEPTH(type) )
    {
    case CV_8U:
        t = ((uchar*)ptr)[coi];
        break;
    case CV_8S:
        t = ((char*)ptr)[coi];
        break;
    case CV_16S:
        t = ((short*)ptr)[coi];
        break;
    case CV_32S:
        t = ((int*)ptr)[coi];
        break;
    case CV_32F:
        t = ((float*)ptr)[coi];
        break;
    case CV_64F:
        t = ((double*)ptr)[coi];
        break;
    }

    return t;
}

void CvMAT::set( uchar* ptr, int type, int coi, double d )
{
    int i;
    assert( (unsigned)coi < (unsigned)CV_MAT_CN(type) );

    switch( CV_MAT_DEPTH(type))
    {
    case CV_8U:
        i = cvRound(d);
        ((uchar*)ptr)[coi] = CV_CAST_8U(i);
        break;
    case CV_8S:
        i = cvRound(d);
        ((char*)ptr)[coi] = CV_CAST_8S(i);
        break;
    case CV_16S:
        i = cvRound(d);
        ((short*)ptr)[coi] = CV_CAST_16S(i);
        break;
    case CV_32S:
        i = cvRound(d);
        ((int*)ptr)[coi] = CV_CAST_32S(i);
        break;
    case CV_32F:
        ((float*)ptr)[coi] = (float)d;
        break;
    case CV_64F:
        ((double*)ptr)[coi] = d;
        break;
    }
}

void CvMAT::set( uchar* ptr, int type, int coi, int i )
{
    assert( (unsigned)coi < (unsigned)CV_MAT_CN(type) );

    switch( CV_MAT_DEPTH(type))
    {
    case CV_8U:
        ((uchar*)ptr)[coi] = CV_CAST_8U(i);
        break;
    case CV_8S:
        ((char*)ptr)[coi] = CV_CAST_8S(i);
        break;
    case CV_16S:
        ((short*)ptr)[coi] = CV_CAST_16S(i);
        break;
    case CV_32S:
        ((int*)ptr)[coi] = i;
        break;
    case CV_32F:
        ((float*)ptr)[coi] = (float)i;
        break;
    case CV_64F:
        ((double*)ptr)[coi] = (double)i;
        break;
    }
}

void CvMAT::set( uchar* ptr, int type, double d )
{
    int i, cn = CV_MAT_CN(type);

    switch( CV_MAT_DEPTH(type))
    {
    case CV_8U:
        i = cvRound(d);
        ((uchar*)ptr)[0] = CV_CAST_8U(i);
        i = cn;
        while( --i ) ((uchar*)ptr)[i] = 0;
        break;
    case CV_8S:
        i = cvRound(d);
        ((char*)ptr)[0] = CV_CAST_8S(i);
        i = cn;
        while( --i ) ((char*)ptr)[i] = 0;
        break;
    case CV_16S:
        i = cvRound(d);
        ((short*)ptr)[0] = CV_CAST_16S(i);
        i = cn;
        while( --i ) ((short*)ptr)[i] = 0;
        break;
    case CV_32S:
        i = cvRound(d);
        ((int*)ptr)[0] = i;
        i = cn;
        while( --i ) ((int*)ptr)[i] = 0;
        break;
    case CV_32F:
        ((float*)ptr)[0] = (float)d;
        i = cn;
        while( --i ) ((float*)ptr)[i] = 0;
        break;
    case CV_64F:
        ((double*)ptr)[0] = d;
        i = cn;
        while( --i ) ((double*)ptr)[i] = 0;
        break;
    }
}

void CvMAT::set( uchar* ptr, int type, int i )
{
    int cn = CV_MAT_CN(type);

    switch( CV_MAT_DEPTH(type))
    {
    case CV_8U:
        ((uchar*)ptr)[0] = CV_CAST_8U(i);
        i = cn;
        while( --i ) ((uchar*)ptr)[i] = 0;
        break;
    case CV_8S:
        ((char*)ptr)[0] = CV_CAST_8S(i);
        i = cn;
        while( --i ) ((char*)ptr)[i] = 0;
        break;
    case CV_16S:
        ((short*)ptr)[0] = CV_CAST_16S(i);
        i = cn;
        while( --i ) ((short*)ptr)[i] = 0;
        break;
    case CV_32S:
        ((int*)ptr)[0] = i;
        i = cn;
        while( --i ) ((int*)ptr)[i] = 0;
        break;
    case CV_32F:
        ((float*)ptr)[0] = (float)i;
        i = cn;
        while( --i ) ((float*)ptr)[i] = 0;
        break;
    case CV_64F:
        ((double*)ptr)[0] = (double)i;
        i = cn;
        while( --i ) ((double*)ptr)[i] = 0;
        break;
    }
}

CvMAT::CvMAT( const _CvMAT_T_& mat_t )
{
    data.ptr = 0;
    type = 0;
    refcount = 0;
    *this = mat_t;
}

CvMAT::CvMAT( const _CvMAT_ADD_& mat_add )
{
    data.ptr = 0;
    type = 0;
    refcount = 0;
    *this = mat_add;
}

CvMAT::CvMAT( const _CvMAT_ADD_EX_& mat_add )
{
    data.ptr = 0;
    type = 0;
    refcount = 0;
    *this = mat_add;
}

CvMAT::CvMAT( const _CvMAT_SCALE_& scale_mat )
{
    data.ptr = 0;
    type = 0;
    refcount = 0;
    *this = scale_mat;
}

CvMAT::CvMAT( const _CvMAT_SCALE_SHIFT_& scale_shift_mat )
{
    data.ptr = 0;
    type = 0;
    refcount = 0;
    *this = scale_shift_mat;
}

CvMAT::CvMAT( const _CvMAT_MUL_& mmul )
{
    data.ptr = 0;
    type = 0;
    refcount = 0;
    *this = mmul;
}

CvMAT::CvMAT( const _CvMAT_MUL_ADD_& mmuladd )
{
    data.ptr = 0;
    type = 0;
    refcount = 0;
    *this = mmuladd;
}

CvMAT::CvMAT( const _CvMAT_INV_& inv_mat )
{
    data.ptr = 0;
    type = 0;
    refcount = 0;
    *this = inv_mat;
}

CvMAT::CvMAT( const _CvMAT_NOT_& not_mat )
{
    type = 0;
    data.ptr = 0;
    refcount = 0;
    *this = not_mat;
}

CvMAT::CvMAT( const _CvMAT_UN_LOGIC_& mat_logic )
{
    type = 0;
    data.ptr = 0;
    refcount = 0;
    *this = mat_logic;
}

CvMAT::CvMAT( const _CvMAT_LOGIC_& mat_logic )
{
    type = 0;
    data.ptr = 0;
    refcount = 0;
    *this = mat_logic;
}

CvMAT::CvMAT( const _CvMAT_COPY_& mat_copy )
{
    CvMAT* src = (CvMAT*)mat_copy.a;
    create( src->height, src->width, src->type );
    cvCopy( src, this );
}

CvMAT::CvMAT( const _CvMAT_CVT_& mat_cvt )
{
    type = 0;
    data.ptr = 0;
    refcount = 0;
    *this = mat_cvt;
}

CvMAT::CvMAT( const _CvMAT_DOT_OP_& dot_op )
{
    data.ptr = 0;
    type = 0;
    refcount = 0;
    *this = dot_op;
}

CvMAT::CvMAT( const _CvMAT_SOLVE_& solve_mat )
{
    type = 0;
    data.ptr = 0;
    refcount = 0;
    *this = solve_mat;
}

CvMAT::CvMAT( const _CvMAT_CMP_& cmp_mat )
{
    type = 0;
    data.ptr = 0;
    refcount = 0;
    *this = cmp_mat;
}

/****************************************************************************************\
*                                  CvMAT::operator =                                     *
\****************************************************************************************/

CvMAT& CvMAT::operator = ( const _CvMAT_T_& mat_t )
{
    CvMAT* src = (CvMAT*)&mat_t.a;
    if( !data.ptr )
    {
        create( src->width, src->height, src->type );
    }

    cvTranspose( src, this );
    return *this;
}

CvMAT& CvMAT::operator = ( const _CvMAT_ADD_& mat_add )
{
    CvMAT* a = mat_add.a;
    CvMAT* b = mat_add.b;

    if( !data.ptr )
    {
        create( a->height, a->width, a->type );
    }

    if( mat_add.beta == 1 )
    {
        cvAdd( a, b, this );
        return *this;
    }

    if( mat_add.beta == -1 )
    {
        cvSub( a, b, this );
        return *this;
    }

    if( CV_MAT_DEPTH(a->type) >= CV_32F && CV_MAT_CN(a->type) <= 2 )
        cvScaleAdd( b, cvScalar(mat_add.beta), a, this );
    else
        cvAddWeighted( a, 1, b, mat_add.beta, 0, this );
    return *this;
}

CvMAT& CvMAT::operator = ( const _CvMAT_ADD_EX_& mat_add )
{
    CvMAT* a = mat_add.a;
    CvMAT* b = mat_add.b;

    if( !data.ptr )
    {
        create( a->height, a->width, a->type );
    }

    cvAddWeighted( a, mat_add.alpha, b, mat_add.beta, mat_add.gamma, this );
    return *this;
}

CvMAT& CvMAT::operator = ( const _CvMAT_SCALE_& scale_mat )
{
    CvMAT* src = scale_mat.a;

    if( !data.ptr )
    {
        create( src->height, src->width, src->type );
    }

    cvConvertScale( src, this, scale_mat.alpha, 0 );
    return *this;
}

CvMAT& CvMAT::operator = ( const _CvMAT_SCALE_SHIFT_& scale_shift_mat )
{
    CvMAT* src = scale_shift_mat.a;

    if( !data.ptr )
    {
        create( src->height, src->width, src->type );
    }

    cvConvertScale( src, this, scale_shift_mat.alpha, scale_shift_mat.beta );
    return *this;
}

CvMAT& CvMAT::operator = ( const _CvMAT_MUL_& mmul )
{
    CvMAT* a = mmul.a;
    CvMAT* b = mmul.b;
    int t_a = mmul.t_ab & 1;
    int t_b = (mmul.t_ab & 2) != 0;
    int m = (&(a->rows))[t_a];
    int n = (&(b->rows))[t_b ^ 1];
    /* this(m x n) = (a^o1(t))(m x l) * (b^o2(t))(l x n) */

    if( !data.ptr )
    {
        create( m, n, a->type );
    }

    if( mmul.alpha == 1 )
    {
        if( mmul.t_ab == 0 )
        {
            cvMatMulAdd( a, b, 0, this );
            return *this;
        }

        if( a->data.ptr == b->data.ptr && mmul.t_ab < 3 &&
            a->rows == b->rows && a->cols == b->cols &&
            a->data.ptr != data.ptr )
        {
            cvMulTransposed( a, this, mmul.t_ab & 1 );
            return *this;
        }
    }

    cvGEMM( a, b, mmul.alpha, 0, 0, this, mmul.t_ab );
    return *this;
}

CvMAT& CvMAT::operator = ( const _CvMAT_MUL_ADD_& mmuladd )
{
    CvMAT* a = mmuladd.a;
    CvMAT* b = mmuladd.b;
    CvMAT* c = mmuladd.c;
    int t_a = mmuladd.t_abc & 1;
    int t_b = (mmuladd.t_abc & 2) != 0;
    int m = (&(a->rows))[t_a];
    int n = (&(b->rows))[t_b ^ 1];
    /* this(m x n) = (a^o1(t))(m x l) * (b^o2(t))(l x n) */

    if( !data.ptr )
    {
        create( m, n, a->type );
    }

    if( mmuladd.t_abc == 0 && mmuladd.alpha == 1 && mmuladd.beta == 1 )
        cvMatMulAdd( a, b, c, this );
    else
        cvGEMM( a, b, mmuladd.alpha, c, mmuladd.beta, this, mmuladd.t_abc );
    return *this;
}

CvMAT& CvMAT::operator = ( const _CvMAT_INV_& inv_mat )
{
    CvMAT* src = (CvMAT*)&inv_mat.a;

    if( !data.ptr )
    {
        create( src->height, src->width, src->type );
    }

    if( inv_mat.method == 0 )
        cvInvert( src, this );
    else
        cvPseudoInv( src, this );
    return *this;
}

CvMAT& CvMAT::operator = ( const _CvMAT_NOT_& not_mat )
{
    CvMAT* src = not_mat.a;

    if( !data.ptr )
    {
        create( src->height, src->width, src->type );
    }

    cvNot( src, this );
    return *this;
}

CvMAT& CvMAT::operator = ( const _CvMAT_LOGIC_& mat_logic )
{
    CvMAT* a = mat_logic.a;
    CvMAT* b = mat_logic.b;
    int flags = mat_logic.flags;
    _CvMAT_LOGIC_::Op op = mat_logic.op;

    if( !data.ptr )
    {
        create( a->height, a->width, a->type );
    }

    switch( op )
    {
    case _CvMAT_LOGIC_::AND:

        if( flags == 0 )
            cvAnd( a, b, this );
        else if( flags == 3 )
        {
            cvOr( a, b, this );
            cvNot( this, this );
        }
        else if( flags == 1 )
        {
            if( data.ptr == b->data.ptr )
            {
                cvNot( b, this );
                cvOr( this, a, this );
                cvNot( this, this );
            }
            else
            {
                cvNot( a, this );
                cvAnd( this, b, this );
            }
        }
        else
        {
            if( data.ptr == a->data.ptr )
            {
                cvNot( a, this );
                cvOr( this, b, this );
                cvNot( this, this );
            }
            else
            {
                cvNot( b, this );
                cvAnd( this, a, this );
            }
        }
        break;

    case _CvMAT_LOGIC_::OR:

        if( flags == 0 )
            cvOr( a, b, this );
        else if( flags == 3 )
        {
            cvAnd( a, b, this );
            cvNot( this, this );
        }
        else if( flags == 1 )
        {
            if( data.ptr == b->data.ptr )
            {
                cvNot( b, this );
                cvAnd( this, a, this );
                cvNot( this, this );
            }
            else
            {
                cvNot( a, this );
                cvOr( this, b, this );
            }
        }
        else
        {
            if( data.ptr == a->data.ptr )
            {
                cvNot( a, this );
                cvAnd( this, b, this );
                cvNot( this, this );
            }
            else
            {
                cvNot( b, this );
                cvOr( this, a, this );
            }
        }
        break;

    case _CvMAT_LOGIC_::XOR:

        cvXor( a, b, this );
        if( flags == 1 || flags == 2 )
            cvNot( this, this );
        break;
    }

    return *this;
}

CvMAT& CvMAT::operator = ( const _CvMAT_UN_LOGIC_& mat_logic )
{
    CvMAT* a = mat_logic.a;
    CvScalar scalar = cvScalarAll( mat_logic.alpha );
    int flags = mat_logic.flags;
    _CvMAT_LOGIC_::Op op = mat_logic.op;

    if( !data.ptr )
    {
        create( a->height, a->width, a->type );
    }

    switch( op )
    {
    case _CvMAT_LOGIC_::AND:

        if( flags == 0 )
            cvAndS( a, scalar, this );
        else
        {
            cvNot( a, this );
            cvAndS( this, scalar, this );
        }
        break;

    case _CvMAT_LOGIC_::OR:

        if( flags == 0 )
            cvOrS( a, scalar, this );
        else
        {
            cvNot( a, this );
            cvOrS( this, scalar, this );
        }
        break;

    case _CvMAT_LOGIC_::XOR:

        if( flags == 0 )
            cvXorS( a, scalar, this );
        else
            cvXorS( a, ~scalar, this );
        break;
    }

    return *this;
}

CvMAT& CvMAT::operator = ( const _CvMAT_COPY_& mat_copy )
{
    CvMAT* src = (CvMAT*)mat_copy.a;

    if( !data.ptr )
    {
        create( src->height, src->width, src->type );
    }

    if( src != this )
        cvCopy( src, this );

    return *this;
}

CvMAT& CvMAT::operator = ( const _CvMAT_CVT_& mat_cvt )
{
    CvMAT* src = (CvMAT*)&mat_cvt.a;

    if( !data.ptr )
    {
        int depth = mat_cvt.newdepth;
        create( src->height, src->width, depth < 0 ? src->type :
                CV_MAT_CN(src->type)|CV_MAT_DEPTH(depth));
    }

    cvCvtScale( src, this, mat_cvt.scale, mat_cvt.shift );
    return *this;
}

CvMAT& CvMAT::operator = ( const _CvMAT_DOT_OP_& dot_op )
{
    CvMAT* a = (CvMAT*)&(dot_op.a);
    CvMAT* b = dot_op.b;

    if( !data.ptr )
    {
        create( a->height, a->width, a->type );
    }

    switch( dot_op.op )
    {
    case '*':
        cvMul( a, b, this, dot_op.alpha );
        break;
    case '/':
        if( b != 0 )
            cvDiv( a, b, this, dot_op.alpha );
        else
            cvDiv( 0, a, this, dot_op.alpha );
        break;
    case 'm':
        if( b != 0 )
            cvMin( a, b, this );
        else
            cvMinS( a, dot_op.alpha, this );
        break;
    case 'M':
        if( b != 0 )
            cvMax( a, b, this );
        else
            cvMaxS( a, dot_op.alpha, this );
        break;
    case 'a':
        if( b != 0 )
            cvAbsDiff( a, b, this );
        else
            cvAbsDiffS( a, this, cvScalar(dot_op.alpha) );
        break;
    default:
        assert(0);
    }

    return *this;
}

CvMAT& CvMAT::operator = ( const _CvMAT_SOLVE_& solve_mat )
{
    CvMAT* a = (CvMAT*)(solve_mat.a);
    CvMAT* b = (CvMAT*)(solve_mat.b);

    if( !data.ptr )
    {
        create( a->height, b->width, a->type );
    }

    if( solve_mat.method == 0 )
        cvSolve( a, b, this );
    else
    {
        CvMAT temp;
        cvInitMatHeader( &temp, a->cols, a->rows, a->type );
        cvCreateData( &temp );

        cvPseudoInv( a, &temp );
        cvMatMul( &temp, b, this );
    }

    return *this;
}

CvMAT& CvMAT::operator = ( const _CvMAT_CMP_& mat_cmp )
{
    CvMAT* a = mat_cmp.a;
    CvMAT* b = mat_cmp.b;

    if( !data.ptr )
    {
        create( a->height, a->width, CV_8UC1 );
    }

    if( b )
        cvCmp( a, b, this, mat_cmp.cmp_op );
    else
        cvCmpS( a, mat_cmp.alpha, this, mat_cmp.cmp_op );
    return *this;
}

/****************************************************************************************\
*                                  CvMAT I/O operations                                  *
\****************************************************************************************/

void  CvMAT::write( const char* name, FILE* f, const char* fmt )
{
    int i, j, w = width * CV_MAT_CN(type);
    FILE* out = f ? f : stdout;

    if( name )
        fprintf( stdout, "%s(%d x %d) =\n\t", name, rows, cols );

    for( i = 0; i < rows; i++ )
    {
        switch( CV_MAT_DEPTH(type))
        {
        case CV_8U: if( !fmt )
                        fmt = "%4d";
                    for( j = 0; j < w; j++ )
                        fprintf( out, fmt, ((uchar*)(data.ptr + i*step))[j] );
                    break;
        case CV_8S: if( !fmt )
                        fmt = "%5d";
                    for( j = 0; j < w; j++ )
                        fprintf( out, fmt, ((char*)(data.ptr + i*step))[j] );
                    break;
        case CV_16S: if( !fmt )
                        fmt = "%7d";
                    for( j = 0; j < w; j++ )
                        fprintf( out, fmt, ((short*)(data.ptr + i*step))[j] );
                    break;
        case CV_32S: if( !fmt )
                        fmt = " %08x";
                    for( j = 0; j < w; j++ )
                        fprintf( out, fmt, ((int*)(data.ptr + i*step))[j] );
                    break;
        case CV_32F: if( !fmt )
                        fmt = "%15g";
                    for( j = 0; j < w; j++ )
                        fprintf( out, fmt, ((float*)(data.ptr + i*step))[j] );
                    break;
        case CV_64F: if( !fmt )
                        fmt = "%15g";
                    for( j = 0; j < w; j++ )
                        fprintf( out, fmt, ((double*)(data.ptr + i*step))[j] );
                    break;
        }
        fprintf( out, "\n%s", i < rows - 1 ? "\t" : "" );
    }
    fprintf( out, "\n" );
}

#endif /* _MSC_VER || __BORLANDC__ */

/* End of file. */

<commit_msg>removed obsolete matrix expression implementation<commit_after><|endoftext|>