<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program; if not, write to the Free Software Foundation, Inc., 51  *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include "Sofa_test.h"
#include <SofaComponentMain/init.h>
#include <sofa/simulation/graph/DAGSimulation.h>
#include <sofa/defaulttype/VecTypes.h>
#include <SofaBaseTopology/PointSetTopologyContainer.h>
#include <SofaConstraint/BilateralInteractionConstraint.h>
#include <SofaBaseMechanics/MechanicalObject.h>
#include <sofa/core/MechanicalParams.h>

#include <sofa/simulation/common/SceneLoaderXML.h>

namespace sofa {

namespace {

using std::cout;
using std::cerr;
using std::endl;
using namespace component;
using namespace defaulttype;

template <typename _DataTypes>
struct BilateralInteractionConstraint_test : public Sofa_test<typename _DataTypes::Real>
{
    typedef _DataTypes DataTypes;
    typedef typename DataTypes::VecCoord VecCoord;
    typedef typename DataTypes::VecDeriv VecDeriv;
    typedef typename DataTypes::Coord Coord;
    typedef typename DataTypes::Deriv Deriv;
    typedef typename DataTypes::CPos CPos;
    typedef typename Coord::value_type Real;
    typedef constraintset::BilateralInteractionConstraint<DataTypes> BilateralInteractionConstraint;
    typedef component::topology::PointSetTopologyContainer PointSetTopologyContainer;
    typedef container::MechanicalObject<DataTypes> MechanicalObject;

    simulation::Node::SPtr root;                 ///< Root of the scene graph, created by the constructor an re-used in the tests
    simulation::Simulation* simulation;          ///< created by the constructor an re-used in the tests

    /// Create the context for the tests.
    void SetUp()
    {
        sofa::component::init();
        sofa::simulation::setSimulation(simulation = new sofa::simulation::graph::DAGSimulation());

        /// Load the scene
        std::string sceneName = "BilateralInteractionConstraint.scn";
        std::string fileName  = std::string(SOFATEST_SCENES_DIR) + "/" + sceneName;
        root = sofa::core::objectmodel::SPtr_dynamic_cast<sofa::simulation::Node>( sofa::simulation::getSimulation()->load(fileName.c_str()));

        // Test if load has succeeded
        sofa::simulation::SceneLoaderXML scene;

        if(!root || !scene.loadSucceed)
        {
            ADD_FAILURE() << "Error while loading the scene: " << sceneName << std::endl;
        }
    }

    void init_Setup()
    {
        /// Init
        sofa::simulation::getSimulation()->init(root.get());
    }

    bool test_constrainedPositions()
    {
        std::vector<MechanicalObject*> meca;
        root->get<MechanicalObject>(&meca,std::string("mecaConstraint"),root->SearchDown);

        std::vector<Coord> points;
        points.resize(2);

        if(meca.size()==2)
        {
            for(int i=0; i<meca.size(); i++)
                points[i]=(*meca[i]->getX())[0];
        }
        else
        {
            ADD_FAILURE() << "Error while searching mechanical object" << std::endl;
        }

        for(int i=0; i<10; i++)
            sofa::simulation::getSimulation()->animate(root.get(),(double)0.001);

        if(points[0] == points[1]) return true;
        else
        {
            ADD_FAILURE() << "Error while testing if two positions are correctly constrained" << std::endl;
        }

        return false;
    }

 };

// Define the list of DataTypes to instanciate
using testing::Types;
typedef Types<Vec3Types> DataTypes; // the types to instanciate.

// Test suite for all the instanciations
TYPED_TEST_CASE(BilateralInteractionConstraint_test, DataTypes);
TYPED_TEST( BilateralInteractionConstraint_test , constrainedPositions )
{
    this->init_Setup();
    ASSERT_TRUE(  this->test_constrainedPositions() );
}

}

} // namespace sofa

<commit_msg>Add : test BilateralIteractionConstraint<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program; if not, write to the Free Software Foundation, Inc., 51  *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include "Sofa_test.h"
#include <SofaComponentMain/init.h>
#include <sofa/simulation/graph/DAGSimulation.h>
#include <sofa/defaulttype/VecTypes.h>
#include <SofaBaseTopology/PointSetTopologyContainer.h>
#include <SofaConstraint/BilateralInteractionConstraint.h>
#include <SofaBaseMechanics/MechanicalObject.h>
#include <sofa/core/MechanicalParams.h>
#include <sofa/defaulttype/VecTypes.h>

#include <sofa/simulation/common/SceneLoaderXML.h>

namespace sofa {

namespace {

using std::cout;
using std::cerr;
using std::endl;
using namespace component;
using namespace defaulttype;

template <typename _DataTypes>
struct BilateralInteractionConstraint_test : public Sofa_test<typename _DataTypes::Real>
{
    typedef _DataTypes DataTypes;
    typedef typename DataTypes::VecCoord VecCoord;
    typedef typename DataTypes::VecDeriv VecDeriv;
    typedef typename DataTypes::Coord Coord;
    typedef typename DataTypes::Deriv Deriv;
    typedef typename DataTypes::CPos CPos;
    typedef typename Coord::value_type Real;
    typedef constraintset::BilateralInteractionConstraint<DataTypes> BilateralInteractionConstraint;
    typedef component::topology::PointSetTopologyContainer PointSetTopologyContainer;
    typedef container::MechanicalObject<DataTypes> MechanicalObject;

    simulation::Node::SPtr root;                 ///< Root of the scene graph, created by the constructor an re-used in the tests
    simulation::Simulation* simulation;          ///< created by the constructor an re-used in the tests

    /// Create the context for the tests.
    void SetUp()
    {
        sofa::component::init();
        sofa::simulation::setSimulation(simulation = new sofa::simulation::graph::DAGSimulation());

        /// Load the scene
        std::string sceneName = "BilateralInteractionConstraint.scn";
        std::string fileName  = std::string(SOFATEST_SCENES_DIR) + "/" + sceneName;
        root = sofa::core::objectmodel::SPtr_dynamic_cast<sofa::simulation::Node>( sofa::simulation::getSimulation()->load(fileName.c_str()));

        // Test if load has succeeded
        sofa::simulation::SceneLoaderXML scene;

        if(!root || !scene.loadSucceed)
        {
            ADD_FAILURE() << "Error while loading the scene: " << sceneName << std::endl;
        }
    }

    void init_Setup()
    {
        /// Init
        sofa::simulation::getSimulation()->init(root.get());
    }

    bool test_constrainedPositions()
    {
        std::vector<MechanicalObject*> meca;
        root->get<MechanicalObject>(&meca,std::string("mecaConstraint"),root->SearchDown);

        std::vector<Coord> points;
        points.resize(2);

        if(meca.size()==2)
        {
            for(int i=0; i<meca.size(); i++)
                points[i]=(*meca[i]->getX())[0];
        }
        else
        {
            ADD_FAILURE() << "Error while searching mechanical object" << std::endl;
        }

        for(int i=0; i<10; i++)
            sofa::simulation::getSimulation()->animate(root.get(),(double)0.001);

        if(points[0] == points[1]) return true;
        else
        {
            ADD_FAILURE() << "Error while testing if two positions are correctly constrained" << std::endl;
        }

        return false;
    }

 };

// Define the list of DataTypes to instanciate
using testing::Types;
typedef Types<Vec3Types> DataTypes; // the types to instanciate.

// Test suite for all the instanciations
TYPED_TEST_CASE(BilateralInteractionConstraint_test, DataTypes);
TYPED_TEST( BilateralInteractionConstraint_test , constrainedPositions )
{
    this->init_Setup();
    ASSERT_TRUE(  this->test_constrainedPositions() );
}

}

} // namespace sofa

<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#include <vexcl/vexcl.hpp>

#include <boost/compute.hpp>

#include <algorithm>
#include <QtGui>
#include <QtOpenGL>
#include <boost/compute/command_queue.hpp>
#include <boost/compute/kernel.hpp>
#include <boost/compute/program.hpp>
#include <boost/compute/source.hpp>
#include <boost/compute/system.hpp>
#include <boost/compute/interop/opengl.hpp>

using namespace std;
namespace compute = boost::compute;

int main (int argc, char* argv[])
{
    // get the default compute device
    compute::device gpu = compute::system::default_device();

    // create a compute context and command queue
    compute::context ctx(gpu);
    compute::command_queue queue(ctx, gpu);

	//set some default values for when no commandline arguments are given
        //create accuracy variable
        //int accuracy = 90;
        // create data array on host
        int host_data[] = { 1, 3, 5, 7, 9 };

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

        //create polygons variable
        //int polygons = 50;
        // create data array on host
        int host_data[] = { 1, 3, 5, 7, 9 };

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

        //create vertices variable
        //int vertices = 6;
        // create data array on host
        int host_data[] = { 1, 3, 5, 7, 9 };

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

    //read input commandline arguments
    for (int i = 1; i < argc; ++i)
    {
        if (std::string(argv[i]) == "-a")
            {
                //initialise desired accuracy variable according to commandline argument -a
                accuracy = ;

            }
        if (std::string(argv[i]) == "-p")
            {
                //initialise maximum polygons variable according to commandline argument -p
                polygons = ;

            }
        if (std::string(argv[i]) == "-v")
            {
                //initialise maximum verices per polygon variable according to commandline argument -v
                vertices = ;

            }
    }

    //create leaderDNA variable
        // create data array on host
        int host_data[] = { 1, 3, 5, 7, 9 };

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

    //create mutatedDNA variable
        // create data array on host
        int host_data[] = { 1, 3, 5, 7, 9 };

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

    //create leaderDNArender variable
        // create data array on host
        int host_data[] = { 1, 3, 5, 7, 9 };

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

    //create mutatedDNArender variable
        // create data array on host
        int host_data[] = { 1, 3, 5, 7, 9 };

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

    //create original image variable + load image into gpu memory
    if (std::string(argv[i]) == "")
            {
                //load file according to commandline argument into gpu vector

                //get x(max), y(max). (image dimensions)

                //make image vector on device
                compute::vector<float> originalimage(ctx, n);
                // copy data to the device
                compute::copy(
                    host_vector.begin(),
                    host_vector.end(),
                    device_vector.begin(),
                    queue
                );
            }

    //initialise DNA with a random seed
        //create random leader dna
        // generate random dna vector on the host
        std::vector<float> host_vector(1000000);
        std::generate(host_vector.begin(), host_vector.end(), rand);

        // create vector on the device
        compute::vector<float> device_vector(1000000, ctx);

        // copy data to the device
        compute::copy(
            host_vector.begin(),
            host_vector.end(),
            device_vector.begin(),
            queue
        );

    //run render loop until desired accuracy is reached
    while (leaderaccuracy<accuracy)
        {

            //render leader DNA to a raster image in opengl texture
            boost::compute::function<int (int)> renderDNA =
            boost::compute::make_function_from_source<int (int)>(
                "renderDNA",
                "int renderDNA(int x)
                    { //for each shape in dna
                        {
                        glEnable(GL_TEXTURE_2D);
                        glBindTexture(GL_TEXTURE_2D, gl_texture_);
                        glBegin(GL_QUADS);
                        glTexCoord2f(0, 0); glVertex2f(0, 0);
                        glTexCoord2f(0, 1); glVertex2f(0, h);
                        glTexCoord2f(1, 1); glVertex2f(w, h);
                        glTexCoord2f(1, 0); glVertex2f(w, 0);
                        glEnd();
                        } }"
            );

            //calculate leader fitness
            leaderfitness = computefitness(mutatedDNA,originalimage)
            while ()
                {
                //mutate from the leaderDNA
                boost::compute::function<int (int)> mutateDNA =
                boost::compute::make_function_from_source<int (int)>(
                    "mutateDNA",
                    "int mutateDNA(int DNA)
                        {
                        //mutate input DNA randomly
                        mutated_shape = RANDINT(NUM_SHAPES);
                        double roulette = RANDDOUBLE(2.8);
                        double drastic = RANDDOUBLE(2);

                        // mutate color
                        if(roulette<1)
                        {
                            if(dna_test[mutated_shape].a < 0.01 // completely transparent shapes are stupid
                            || roulette<0.25)
                        {
                        if(drastic < 1)
                        {
                            dna_test[mutated_shape].a += RANDDOUBLE(0.1);
                        dna_test[mutated_shape].a = CLAMP(dna_test[mutated_shape].a, 0.0, 1.0);
                        }
                        else
                            dna_test[mutated_shape].a = RANDDOUBLE(1.0);
                        }
                        else if(roulette<0.50)
                        {
                        if(drastic < 1)
                        {
                        dna_test[mutated_shape].r += RANDDOUBLE(0.1);
                        dna_test[mutated_shape].r = CLAMP(dna_test[mutated_shape].r, 0.0, 1.0);
                        }
                        else
                        dna_test[mutated_shape].r = RANDDOUBLE(1.0);
                        }
                        else if(roulette<0.75)
                        {
                            if(drastic < 1)
                                {
                                    dna_test[mutated_shape].g += RANDDOUBLE(0.1);
                                    dna_test[mutated_shape].g = CLAMP(dna_test[mutated_shape].g, 0.0, 1.0);
                                }
                            else
                                    dna_test[mutated_shape].g = RANDDOUBLE(1.0);
                        }
                        else
                        {
                        if(drastic < 1)
                        {
                            dna_test[mutated_shape].b += RANDDOUBLE(0.1);
                            dna_test[mutated_shape].b = CLAMP(dna_test[mutated_shape].b, 0.0, 1.0);
                        }
                        else
                            dna_test[mutated_shape].b = RANDDOUBLE(1.0);
                        }
                        }

                        // mutate shape
                        else if(roulette < 2.0)
                        {
                        int point_i = RANDINT(NUM_POINTS);
                        if(roulette<1.5)
                        {
                        if(drastic < 1)
                        {
                            dna_test[mutated_shape].points[point_i].x += (int)RANDDOUBLE(WIDTH/10.0);
                            dna_test[mutated_shape].points[point_i].x = CLAMP(dna_test[mutated_shape].points[point_i].x, 0, WIDTH-1);
                        }
                        else
                            dna_test[mutated_shape].points[point_i].x = RANDDOUBLE(WIDTH);
                        }
                        else
                        {
                        if(drastic < 1)
                        {
                            dna_test[mutated_shape].points[point_i].y += (int)RANDDOUBLE(HEIGHT/10.0);
                            dna_test[mutated_shape].points[point_i].y = CLAMP(dna_test[mutated_shape].points[point_i].y, 0, HEIGHT-1);
                        }
                        else
                            dna_test[mutated_shape].points[point_i].y = RANDDOUBLE(HEIGHT);
                        }
                        }

                        // mutate stacking
                        else
                        {
                            int destination = RANDINT(NUM_SHAPES);
                            shape_t s = dna_test[mutated_shape];
                            dna_test[mutated_shape] = dna_test[destination];
                            dna_test[destination] = s;
                            return destination;
                        }
                        return -1;
                        }"
                );

    //render mutated DNA to a raster image in opengl texture
    boost::compute::function<int (int)> renderDNA =
    boost::compute::make_function_from_source<int (int)>(
        "renderDNA",
        "int renderDNA(int x)
        {
        //for each shape in dna
            {
            glEnable(GL_TEXTURE_2D);
            glBindTexture(GL_TEXTURE_2D, gl_texture_);
            glBegin(GL_QUADS);
            glTexCoord2f(0, 0); glVertex2f(0, 0);
            glTexCoord2f(0, 1); glVertex2f(0, h);
            glTexCoord2f(1, 1); glVertex2f(w, h);
            glTexCoord2f(1, 0); glVertex2f(w, 0);
            glEnd();
            } }"
    );

    //compute fitness of mutated dna image vs leader dna image
    //compute what % match DNAimage is to original image
    boost::compute::function<int (int)> computefitnesspercent =
    boost::compute::make_function_from_source<int (int)>(
        "computefitnesspercent",
        "int computefitnesspercent(int x) { //read leader dna

    //compare input dna to leader dna to find changed polygons
    compareDNA(leaderDNA,DNA);
    //create bounding box containing changed polygons

    //render leader dna within bounding box
    leaderrender = renderDNA(leaderDNA,boundx,boundy);
    //render input dna within bounding box
    inputrender = renderDNA(DNA,boundx,boundy);
    //compare leader and input dna rendered bounding boxes
    compareimage(leaderrender,inputrender);
    //returns % match }"
    );
                //check if it is fitter, if so overwrite leaderDNA
                while (fitness(mutatedDNA,originalimage) < leaderfitness))
                {
                    //overwrite leaderDNA
                    leaderDNA = mutatedDNA;

                    //save dna to disk
                    // start by writing a temp file.
                    pFile = fopen ("volution.dna.temp","w");
                    fprintf (pFile, DNA);
                    fclose (pFile);

                    // Then rename the real backup to a secondary backup.
                    result = rename("volution.dna","volution_2.dna");

                    // Then rename the temp file to the primary backup
                    result = rename("volution.dna.temp","volution.dna");

                    // Then delete the temp file
                    result = remove("volution.dna.temp");
                }
        }
    //perform final render, output svg and raster image
        //render DNA and save resulting image to disk as .svg file and raster image (.png)

    //render image from DNA
    renderDNA(DNA);
    //save resultant image to disk as svg and png files

    //render input DNA to an svg file
    boost::compute::function<int (int)> renderSVG =
    boost::compute::make_function_from_source<int (int)>(
        "renderSVG",
        "int renderSVG(int x) {

            //for each shape in dna
            {
            //add shape to svg file
            }
        }"
    );
}<commit_msg>tidying<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#include <vexcl/vexcl.hpp>

#include <boost/compute.hpp>

#include <algorithm>
#include <QtGui>
#include <QtOpenGL>
#include <boost/compute/command_queue.hpp>
#include <boost/compute/kernel.hpp>
#include <boost/compute/program.hpp>
#include <boost/compute/source.hpp>
#include <boost/compute/system.hpp>
#include <boost/compute/interop/opengl.hpp>

using namespace std;
namespace compute = boost::compute;

int main (int argc, char* argv[])
{
    // get the default compute device
    compute::device gpu = compute::system::default_device();

    // create a compute context and command queue
    compute::context ctx(gpu);
    compute::command_queue queue(ctx, gpu);

	//set some default values for when no commandline arguments are given
        //create accuracy variable
        //int accuracy = 90;
        // create data array on host
        int host_data[] = { 1, 3, 5, 7, 9 };

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

        //create polygons variable
        //int polygons = 50;
        // create data array on host
        int host_data[] = { 1, 3, 5, 7, 9 };

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

        //create vertices variable
        //int vertices = 6;
        // create data array on host
        int host_data[] = { 1, 3, 5, 7, 9 };

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

    //read input commandline arguments
    for (int i = 1; i < argc; ++i)
    {
        if (std::string(argv[i]) == "-a")
            {
                //initialise desired accuracy variable according to commandline argument -a
                accuracy = ;

            }
        if (std::string(argv[i]) == "-p")
            {
                //initialise maximum polygons variable according to commandline argument -p
                polygons = ;

            }
        if (std::string(argv[i]) == "-v")
            {
                //initialise maximum verices per polygon variable according to commandline argument -v
                vertices = ;

            }
    }

    //create leaderDNA variable
        // create data array on host
        int host_data[] = { 1, 3, 5, 7, 9 };

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

    //create mutatedDNA variable
        // create data array on host
        int host_data[] = { 1, 3, 5, 7, 9 };

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

    //create leaderDNArender variable
        // create data array on host
        int host_data[] = { 1, 3, 5, 7, 9 };

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

    //create mutatedDNArender variable
        // create data array on host
        int host_data[] = { 1, 3, 5, 7, 9 };

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

    //create original image variable + load image into gpu memory
    if (std::string(argv[i]) == "")
            {
                //load file according to commandline argument into gpu vector

                //get x(max), y(max). (image dimensions)

                //make image vector on device
                compute::vector<float> originalimage(ctx, n);
                // copy data to the device
                compute::copy(
                    host_vector.begin(),
                    host_vector.end(),
                    device_vector.begin(),
                    queue
                );
            }

    //initialise DNA with a random seed
        //create random leader dna
        // generate random dna vector on the host
        std::vector<float> host_vector(1000000);
        std::generate(host_vector.begin(), host_vector.end(), rand);

        // create vector on the device
        compute::vector<float> device_vector(1000000, ctx);

        // copy data to the device
        compute::copy(
            host_vector.begin(),
            host_vector.end(),
            device_vector.begin(),
            queue
        );

    //run render loop until desired accuracy is reached
    while (leaderaccuracy<accuracy)
        {

            //render leader DNA to a raster image in opengl texture
            boost::compute::function<int (int)> renderDNA =
            boost::compute::make_function_from_source<int (int)>(
                "renderDNA",
                "int renderDNA(int x)
                    { //for each shape in dna
                        {
                        glEnable(GL_TEXTURE_2D);
                        glBindTexture(GL_TEXTURE_2D, gl_texture_);
                        glBegin(GL_QUADS);
                        glTexCoord2f(0, 0); glVertex2f(0, 0);
                        glTexCoord2f(0, 1); glVertex2f(0, h);
                        glTexCoord2f(1, 1); glVertex2f(w, h);
                        glTexCoord2f(1, 0); glVertex2f(w, 0);
                        glEnd();
                        } }"
            );

            //compute fitness of leader dna image
    //compute what % match DNAimage is to original image
    boost::compute::function<int (int)> computefitnesspercent =
    boost::compute::make_function_from_source<int (int)>(
        "computefitnesspercent",
        "int computefitnesspercent(int x) { //read leader dna

    //compare input dna to leader dna to find changed polygons
    compareDNA(leaderDNA,DNA);
    //create bounding box containing changed polygons

    //render leader dna within bounding box
    leaderrender = renderDNA(leaderDNA,boundx,boundy);
    //render input dna within bounding box
    inputrender = renderDNA(DNA,boundx,boundy);
    //compare leader and input dna rendered bounding boxes
    compareimage(leaderrender,inputrender);
    //returns % match }"
    );
            while ()
                {
                //mutate from the leaderDNA
                boost::compute::function<int (int)> mutateDNA =
                boost::compute::make_function_from_source<int (int)>(
                    "mutateDNA",
                    "int mutateDNA(int DNA)
                        {
                        //mutate input DNA randomly
                        mutated_shape = RANDINT(NUM_SHAPES);
                        double roulette = RANDDOUBLE(2.8);
                        double drastic = RANDDOUBLE(2);

                        // mutate color
                        if(roulette<1)
                        {
                            if(dna_test[mutated_shape].a < 0.01 // completely transparent shapes are stupid
                            || roulette<0.25)
                        {
                        if(drastic < 1)
                        {
                            dna_test[mutated_shape].a += RANDDOUBLE(0.1);
                        dna_test[mutated_shape].a = CLAMP(dna_test[mutated_shape].a, 0.0, 1.0);
                        }
                        else
                            dna_test[mutated_shape].a = RANDDOUBLE(1.0);
                        }
                        else if(roulette<0.50)
                        {
                        if(drastic < 1)
                        {
                        dna_test[mutated_shape].r += RANDDOUBLE(0.1);
                        dna_test[mutated_shape].r = CLAMP(dna_test[mutated_shape].r, 0.0, 1.0);
                        }
                        else
                        dna_test[mutated_shape].r = RANDDOUBLE(1.0);
                        }
                        else if(roulette<0.75)
                        {
                            if(drastic < 1)
                                {
                                    dna_test[mutated_shape].g += RANDDOUBLE(0.1);
                                    dna_test[mutated_shape].g = CLAMP(dna_test[mutated_shape].g, 0.0, 1.0);
                                }
                            else
                                    dna_test[mutated_shape].g = RANDDOUBLE(1.0);
                        }
                        else
                        {
                        if(drastic < 1)
                        {
                            dna_test[mutated_shape].b += RANDDOUBLE(0.1);
                            dna_test[mutated_shape].b = CLAMP(dna_test[mutated_shape].b, 0.0, 1.0);
                        }
                        else
                            dna_test[mutated_shape].b = RANDDOUBLE(1.0);
                        }
                        }

                        // mutate shape
                        else if(roulette < 2.0)
                        {
                        int point_i = RANDINT(NUM_POINTS);
                        if(roulette<1.5)
                        {
                        if(drastic < 1)
                        {
                            dna_test[mutated_shape].points[point_i].x += (int)RANDDOUBLE(WIDTH/10.0);
                            dna_test[mutated_shape].points[point_i].x = CLAMP(dna_test[mutated_shape].points[point_i].x, 0, WIDTH-1);
                        }
                        else
                            dna_test[mutated_shape].points[point_i].x = RANDDOUBLE(WIDTH);
                        }
                        else
                        {
                        if(drastic < 1)
                        {
                            dna_test[mutated_shape].points[point_i].y += (int)RANDDOUBLE(HEIGHT/10.0);
                            dna_test[mutated_shape].points[point_i].y = CLAMP(dna_test[mutated_shape].points[point_i].y, 0, HEIGHT-1);
                        }
                        else
                            dna_test[mutated_shape].points[point_i].y = RANDDOUBLE(HEIGHT);
                        }
                        }

                        // mutate stacking
                        else
                        {
                            int destination = RANDINT(NUM_SHAPES);
                            shape_t s = dna_test[mutated_shape];
                            dna_test[mutated_shape] = dna_test[destination];
                            dna_test[destination] = s;
                            return destination;
                        }
                        return -1;
                        }"
                );

    //render mutated DNA to a raster image in opengl texture
    boost::compute::function<int (int)> renderDNA =
    boost::compute::make_function_from_source<int (int)>(
        "renderDNA",
        "int renderDNA(int x)
        {
        //for each shape in dna
            {
            glEnable(GL_TEXTURE_2D);
            glBindTexture(GL_TEXTURE_2D, gl_texture_);
            glBegin(GL_QUADS);
            glTexCoord2f(0, 0); glVertex2f(0, 0);
            glTexCoord2f(0, 1); glVertex2f(0, h);
            glTexCoord2f(1, 1); glVertex2f(w, h);
            glTexCoord2f(1, 0); glVertex2f(w, 0);
            glEnd();
            } }"
    );

    //compute fitness of mutated dna image vs leader dna image
    //compute what % match DNAimage is to original image
    boost::compute::function<int (int)> computefitnesspercent =
    boost::compute::make_function_from_source<int (int)>(
        "computefitnesspercent",
        "int computefitnesspercent(int x) { //read leader dna

    //compare input dna to leader dna to find changed polygons
    compareDNA(leaderDNA,DNA);
    //create bounding box containing changed polygons

    //render leader dna within bounding box
    leaderrender = renderDNA(leaderDNA,boundx,boundy);
    //render input dna within bounding box
    inputrender = renderDNA(DNA,boundx,boundy);
    //compare leader and input dna rendered bounding boxes
    compareimage(leaderrender,inputrender);
    //returns % match }"
    );
                //check if it is fitter, if so overwrite leaderDNA
                while (fitness(mutatedDNA,originalimage) < leaderfitness))
                {
                    //overwrite leaderDNA
                    leaderDNA = mutatedDNA;

                    //save dna to disk
                    // start by writing a temp file.
                    pFile = fopen ("volution.dna.temp","w");
                    fprintf (pFile, DNA);
                    fclose (pFile);

                    // Then rename the real backup to a secondary backup.
                    result = rename("volution.dna","volution_2.dna");

                    // Then rename the temp file to the primary backup
                    result = rename("volution.dna.temp","volution.dna");

                    // Then delete the temp file
                    result = remove("volution.dna.temp");
                }
        }
    //perform final render, output svg and raster image
        //render DNA and save resulting image to disk as .svg file and raster image (.png)

    //render image from DNA
    renderDNA(DNA);
    //save resultant image to disk as svg and png files

    //render input DNA to an svg file
    boost::compute::function<int (int)> renderSVG =
    boost::compute::make_function_from_source<int (int)>(
        "renderSVG",
        "int renderSVG(int x) {

            //for each shape in dna
            {
            //add shape to svg file
            }
        }"
    );
}<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/http/des.h"

#include "base/logging.h"

#if defined(USE_OPENSSL)
#include <openssl/des.h>
#include "base/openssl_util.h"
#elif defined(USE_NSS)
#include <nss.h>
#include <pk11pub.h>
#include "base/nss_util.h"
#elif defined(USE_OPENSSL)
#ifndef ANDROID
#include "base/openssl_util.h"
#endif
#include <openssl/des.h>
#elif defined(OS_MACOSX)
#include <CommonCrypto/CommonCryptor.h>
#elif defined(OS_WIN)
#include <windows.h>
#include <wincrypt.h>
#include "base/crypto/scoped_capi_types.h"
#endif

// The Mac and Windows (CryptoAPI) versions of DESEncrypt are our own code.
// DESSetKeyParity, DESMakeKey, and the Linux (NSS) version of DESEncrypt are
// based on mozilla/security/manager/ssl/src/nsNTLMAuthModule.cpp,
// CVS rev. 1.14.

/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Mozilla.
 *
 * The Initial Developer of the Original Code is IBM Corporation.
 * Portions created by IBM Corporation are Copyright (C) 2003
 * IBM Corporation. All Rights Reserved.
 *
 * Contributor(s):
 *   Darin Fisher <darin@meer.net>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

// Set odd parity bit (in least significant bit position).
static uint8 DESSetKeyParity(uint8 x) {
  if ((((x >> 7) ^ (x >> 6) ^ (x >> 5) ^
        (x >> 4) ^ (x >> 3) ^ (x >> 2) ^
        (x >> 1)) & 0x01) == 0) {
    x |= 0x01;
  } else {
    x &= 0xfe;
  }
  return x;
}

namespace net {

void DESMakeKey(const uint8* raw, uint8* key) {
  key[0] = DESSetKeyParity(raw[0]);
  key[1] = DESSetKeyParity((raw[0] << 7) | (raw[1] >> 1));
  key[2] = DESSetKeyParity((raw[1] << 6) | (raw[2] >> 2));
  key[3] = DESSetKeyParity((raw[2] << 5) | (raw[3] >> 3));
  key[4] = DESSetKeyParity((raw[3] << 4) | (raw[4] >> 4));
  key[5] = DESSetKeyParity((raw[4] << 3) | (raw[5] >> 5));
  key[6] = DESSetKeyParity((raw[5] << 2) | (raw[6] >> 6));
  key[7] = DESSetKeyParity((raw[6] << 1));
}

#if defined(USE_OPENSSL)

void DESEncrypt(const uint8* key, const uint8* src, uint8* hash) {
  base::EnsureOpenSSLInit();

  DES_key_schedule ks;
  DES_set_key_unchecked(
      reinterpret_cast<const_DES_cblock*>(const_cast<uint8*>(key)), &ks);

  DES_ecb_encrypt(reinterpret_cast<const_DES_cblock*>(const_cast<uint8*>(src)),
                  reinterpret_cast<DES_cblock*>(hash), &ks, DES_ENCRYPT);
}

#elif defined(USE_NSS)

void DESEncrypt(const uint8* key, const uint8* src, uint8* hash) {
  CK_MECHANISM_TYPE cipher_mech = CKM_DES_ECB;
  PK11SlotInfo* slot = NULL;
  PK11SymKey* symkey = NULL;
  PK11Context* ctxt = NULL;
  SECItem key_item;
  SECItem* param = NULL;
  SECStatus rv;
  unsigned int n;

  base::EnsureNSSInit();

  slot = PK11_GetBestSlot(cipher_mech, NULL);
  if (!slot)
    goto done;

  key_item.data = const_cast<uint8*>(key);
  key_item.len = 8;
  symkey = PK11_ImportSymKey(slot, cipher_mech,
                             PK11_OriginUnwrap, CKA_ENCRYPT,
                             &key_item, NULL);
  if (!symkey)
    goto done;

  // No initialization vector required.
  param = PK11_ParamFromIV(cipher_mech, NULL);
  if (!param)
    goto done;

  ctxt = PK11_CreateContextBySymKey(cipher_mech, CKA_ENCRYPT,
                                    symkey, param);
  if (!ctxt)
    goto done;

  rv = PK11_CipherOp(ctxt, hash, reinterpret_cast<int*>(&n), 8,
                     const_cast<uint8*>(src), 8);
  if (rv != SECSuccess)
    goto done;

  // TODO(wtc): Should this be PK11_Finalize?
  rv = PK11_DigestFinal(ctxt, hash+8, &n, 0);
  if (rv != SECSuccess)
    goto done;

 done:
  if (ctxt)
    PK11_DestroyContext(ctxt, PR_TRUE);
  if (symkey)
    PK11_FreeSymKey(symkey);
  if (param)
    SECITEM_FreeItem(param, PR_TRUE);
  if (slot)
    PK11_FreeSlot(slot);
}

#elif defined(OS_MACOSX)

void DESEncrypt(const uint8* key, const uint8* src, uint8* hash) {
  CCCryptorStatus status;
  size_t data_out_moved = 0;
  status = CCCrypt(kCCEncrypt, kCCAlgorithmDES, kCCOptionECBMode,
                   key, 8, NULL, src, 8, hash, 8, &data_out_moved);
  DCHECK(status == kCCSuccess);
  DCHECK(data_out_moved == 8);
}

#elif defined(OS_WIN)

void DESEncrypt(const uint8* key, const uint8* src, uint8* hash) {
  base::ScopedHCRYPTPROV provider;
  if (!CryptAcquireContext(provider.receive(), NULL, NULL, PROV_RSA_FULL,
                           CRYPT_VERIFYCONTEXT))
    return;

  {
    // Import the DES key.
    struct KeyBlob {
      BLOBHEADER header;
      DWORD key_size;
      BYTE key_data[8];
    };
    KeyBlob key_blob;
    key_blob.header.bType = PLAINTEXTKEYBLOB;
    key_blob.header.bVersion = CUR_BLOB_VERSION;
    key_blob.header.reserved = 0;
    key_blob.header.aiKeyAlg = CALG_DES;
    key_blob.key_size = 8;  // 64 bits
    memcpy(key_blob.key_data, key, 8);

    base::ScopedHCRYPTKEY key;
    BOOL import_ok = CryptImportKey(provider,
                                    reinterpret_cast<BYTE*>(&key_blob),
                                    sizeof key_blob, 0, 0, key.receive());
    // Destroy the copy of the key.
    SecureZeroMemory(key_blob.key_data, sizeof key_blob.key_data);
    if (!import_ok)
      return;

    // No initialization vector required.
    DWORD cipher_mode = CRYPT_MODE_ECB;
    if (!CryptSetKeyParam(key, KP_MODE, reinterpret_cast<BYTE*>(&cipher_mode),
                          0))
      return;

    // CryptoAPI requires us to copy the plaintext to the output buffer first.
    CopyMemory(hash, src, 8);
    // Pass a 'Final' of FALSE, otherwise CryptEncrypt appends one additional
    // block of padding to the data.
    DWORD hash_len = 8;
    CryptEncrypt(key, 0, FALSE, 0, hash, &hash_len, 8);
  }
}

#endif

}  // namespace net
<commit_msg>Remove a superfluous Android modification to net/http/des.cc<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/http/des.h"

#include "base/logging.h"

#if defined(USE_OPENSSL)
#include <openssl/des.h>
#include "base/openssl_util.h"
#elif defined(USE_NSS)
#include <nss.h>
#include <pk11pub.h>
#include "base/nss_util.h"
#elif defined(OS_MACOSX)
#include <CommonCrypto/CommonCryptor.h>
#elif defined(OS_WIN)
#include <windows.h>
#include <wincrypt.h>
#include "base/crypto/scoped_capi_types.h"
#endif

// The Mac and Windows (CryptoAPI) versions of DESEncrypt are our own code.
// DESSetKeyParity, DESMakeKey, and the Linux (NSS) version of DESEncrypt are
// based on mozilla/security/manager/ssl/src/nsNTLMAuthModule.cpp,
// CVS rev. 1.14.

/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Mozilla.
 *
 * The Initial Developer of the Original Code is IBM Corporation.
 * Portions created by IBM Corporation are Copyright (C) 2003
 * IBM Corporation. All Rights Reserved.
 *
 * Contributor(s):
 *   Darin Fisher <darin@meer.net>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

// Set odd parity bit (in least significant bit position).
static uint8 DESSetKeyParity(uint8 x) {
  if ((((x >> 7) ^ (x >> 6) ^ (x >> 5) ^
        (x >> 4) ^ (x >> 3) ^ (x >> 2) ^
        (x >> 1)) & 0x01) == 0) {
    x |= 0x01;
  } else {
    x &= 0xfe;
  }
  return x;
}

namespace net {

void DESMakeKey(const uint8* raw, uint8* key) {
  key[0] = DESSetKeyParity(raw[0]);
  key[1] = DESSetKeyParity((raw[0] << 7) | (raw[1] >> 1));
  key[2] = DESSetKeyParity((raw[1] << 6) | (raw[2] >> 2));
  key[3] = DESSetKeyParity((raw[2] << 5) | (raw[3] >> 3));
  key[4] = DESSetKeyParity((raw[3] << 4) | (raw[4] >> 4));
  key[5] = DESSetKeyParity((raw[4] << 3) | (raw[5] >> 5));
  key[6] = DESSetKeyParity((raw[5] << 2) | (raw[6] >> 6));
  key[7] = DESSetKeyParity((raw[6] << 1));
}

#if defined(USE_OPENSSL)

void DESEncrypt(const uint8* key, const uint8* src, uint8* hash) {
  base::EnsureOpenSSLInit();

  DES_key_schedule ks;
  DES_set_key_unchecked(
      reinterpret_cast<const_DES_cblock*>(const_cast<uint8*>(key)), &ks);

  DES_ecb_encrypt(reinterpret_cast<const_DES_cblock*>(const_cast<uint8*>(src)),
                  reinterpret_cast<DES_cblock*>(hash), &ks, DES_ENCRYPT);
}

#elif defined(USE_NSS)

void DESEncrypt(const uint8* key, const uint8* src, uint8* hash) {
  CK_MECHANISM_TYPE cipher_mech = CKM_DES_ECB;
  PK11SlotInfo* slot = NULL;
  PK11SymKey* symkey = NULL;
  PK11Context* ctxt = NULL;
  SECItem key_item;
  SECItem* param = NULL;
  SECStatus rv;
  unsigned int n;

  base::EnsureNSSInit();

  slot = PK11_GetBestSlot(cipher_mech, NULL);
  if (!slot)
    goto done;

  key_item.data = const_cast<uint8*>(key);
  key_item.len = 8;
  symkey = PK11_ImportSymKey(slot, cipher_mech,
                             PK11_OriginUnwrap, CKA_ENCRYPT,
                             &key_item, NULL);
  if (!symkey)
    goto done;

  // No initialization vector required.
  param = PK11_ParamFromIV(cipher_mech, NULL);
  if (!param)
    goto done;

  ctxt = PK11_CreateContextBySymKey(cipher_mech, CKA_ENCRYPT,
                                    symkey, param);
  if (!ctxt)
    goto done;

  rv = PK11_CipherOp(ctxt, hash, reinterpret_cast<int*>(&n), 8,
                     const_cast<uint8*>(src), 8);
  if (rv != SECSuccess)
    goto done;

  // TODO(wtc): Should this be PK11_Finalize?
  rv = PK11_DigestFinal(ctxt, hash+8, &n, 0);
  if (rv != SECSuccess)
    goto done;

 done:
  if (ctxt)
    PK11_DestroyContext(ctxt, PR_TRUE);
  if (symkey)
    PK11_FreeSymKey(symkey);
  if (param)
    SECITEM_FreeItem(param, PR_TRUE);
  if (slot)
    PK11_FreeSlot(slot);
}

#elif defined(OS_MACOSX)

void DESEncrypt(const uint8* key, const uint8* src, uint8* hash) {
  CCCryptorStatus status;
  size_t data_out_moved = 0;
  status = CCCrypt(kCCEncrypt, kCCAlgorithmDES, kCCOptionECBMode,
                   key, 8, NULL, src, 8, hash, 8, &data_out_moved);
  DCHECK(status == kCCSuccess);
  DCHECK(data_out_moved == 8);
}

#elif defined(OS_WIN)

void DESEncrypt(const uint8* key, const uint8* src, uint8* hash) {
  base::ScopedHCRYPTPROV provider;
  if (!CryptAcquireContext(provider.receive(), NULL, NULL, PROV_RSA_FULL,
                           CRYPT_VERIFYCONTEXT))
    return;

  {
    // Import the DES key.
    struct KeyBlob {
      BLOBHEADER header;
      DWORD key_size;
      BYTE key_data[8];
    };
    KeyBlob key_blob;
    key_blob.header.bType = PLAINTEXTKEYBLOB;
    key_blob.header.bVersion = CUR_BLOB_VERSION;
    key_blob.header.reserved = 0;
    key_blob.header.aiKeyAlg = CALG_DES;
    key_blob.key_size = 8;  // 64 bits
    memcpy(key_blob.key_data, key, 8);

    base::ScopedHCRYPTKEY key;
    BOOL import_ok = CryptImportKey(provider,
                                    reinterpret_cast<BYTE*>(&key_blob),
                                    sizeof key_blob, 0, 0, key.receive());
    // Destroy the copy of the key.
    SecureZeroMemory(key_blob.key_data, sizeof key_blob.key_data);
    if (!import_ok)
      return;

    // No initialization vector required.
    DWORD cipher_mode = CRYPT_MODE_ECB;
    if (!CryptSetKeyParam(key, KP_MODE, reinterpret_cast<BYTE*>(&cipher_mode),
                          0))
      return;

    // CryptoAPI requires us to copy the plaintext to the output buffer first.
    CopyMemory(hash, src, 8);
    // Pass a 'Final' of FALSE, otherwise CryptEncrypt appends one additional
    // block of padding to the data.
    DWORD hash_len = 8;
    CryptEncrypt(key, 0, FALSE, 0, hash, &hash_len, 8);
  }
}

#endif

}  // namespace net
<|endoftext|>


<commit_before><commit_msg>Revert "Fix LibreOffice running with SAL_ENABLEGL=1"<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#include <vexcl/vexcl.hpp>

#include <boost/compute.hpp>

#include <algorithm>
#include <QtGui>
#include <QtOpenGL>
#include <boost/compute/command_queue.hpp>
#include <boost/compute/kernel.hpp>
#include <boost/compute/program.hpp>
#include <boost/compute/source.hpp>
#include <boost/compute/system.hpp>
#include <boost/compute/interop/opengl.hpp>

using namespace std;
namespace compute = boost::compute;

int main (int argc, char* argv[])
{
	//set some default values for when no commandline arguments are given
	int accuracy = 90;
	int polygons = 50;
	int vertices = 6;
    //read input commandline arguments
    for (int i = 1; i < argc; ++i)
    {
        if (std::string(argv[i]) == "-a")
            {
                //initialise desired accuracy variable according to commandline argument -a
                accuracy = ;

            }
        if (std::string(argv[i]) == "-p")
            {
                //initialise maximum polygons variable according to commandline argument -p
                polygons = ;

            }
        if (std::string(argv[i]) == "-v")
            {
                //initialise maximum verices per polygon variable according to commandline argument -v
                vertices = ;

            }
    }
     // get the default compute device
    compute::device gpu = compute::system::default_device();

    // create a compute context and command queue
    compute::context ctx(gpu);
    compute::command_queue queue(ctx, gpu);

    //initialise variables in gpu
    const size_t n = 1024 * 1024;
    std::vector<double> leaderDNA(ctx, n);
    std::vector<double> mutatedDNA(ctx, n);
    std::vector<double> leaderDNArender(ctx, n);
    std::vector<double> mutatedDNArender(ctx, n);
    std::vector<double> originalimage(ctx, n);

    //load image into gpu memory
    if (std::string(argv[i]) == "")
            {
                //load file according to commandline argument into gpu vector
                std::vector<double> leaderDNA(ctx, n);
            }
    // copy data to the device
    compute::copy(
        host_vector.begin(),
        host_vector.end(),
        device_vector.begin(),
        queue
    );

    //initialise variables
	class DNA
	{
		public:
		string genome;
        int polygons;
        int vertices;
        polygon[polygons];

	}
    class polygon;
    {
        public:
        int x[vertices];
        int y[vertices];
        int R;
        int G;
        int B;
        int alpha;
    }

    //initialise DNA with a random seed
    leaderDNA = seedDNA();
    //run render loop until desired accuracy is reached
    while (leaderaccuracy<accuracy)
        {
            //mutate from the leaderDNA
            mutatedDNA = mutateDNA(leaderDNA)
            //compute fitness of mutation vs leaderDNA
            //check if it is fitter, if so overwrite leaderDNA
            if (computefitness(leaderDNA,mutatedDNA) == 1)
            {
                //overwrite leaderDNA
                leaderDNA = mutatedDNA;
            }
            //compute accuracy percent
            computefitnesspercent(leaderDNA, originalimage)
        }
    //perform final render, output svg and raster image
    saverender(leaderDNA);
}
int computefitnesspercent (DNA, originalimage)
{
    //compute what % match DNA is to original image
     boost::compute::function<int (int)> computefitnesspercent =
    boost::compute::make_function_from_source<int (int)>(
        "computefitnesspercent",
        "int computefitnesspercent(int x) { //read leader dna

    //compare input dna to leader dna to find changed polygons
    compareDNA(leaderDNA,DNA);
    //create bounding box containing changed polygons

    //render leader dna within bounding box
    leaderrender = renderDNA(leaderDNA,boundx,boundy);
    //render input dna within bounding box
    inputrender = renderDNA(DNA,boundx,boundy);
    //compare leader and input dna rendered bounding boxes
    compareimage(leaderrender,inputrender);
    //returns % match }"
    );
}
int computefitness (DNA0, DNA1)
{
	//compute the fitness of input DNA, i.e. how close is it to original image?
  boost::compute::function<int (int)> computefitness =
    boost::compute::make_function_from_source<int (int)>(
        "computefitness",
        "int computefitness(int x) { //read leader dna

    //compare input dna to leader dna to find changed polygons
    compareDNA(leaderDNA,DNA);
    //create bounding box containing changed polygons

    //render leader dna within bounding box
    leaderrender = renderDNA(leaderDNA,boundx,boundy);
    //render input dna within bounding box
    inputrender = renderDNA(DNA,boundx,boundy);
    //compare leader and input dna rendered bounding boxes
    compareimage(leaderrender,inputrender);
    //returns 1 if dna1 is fitter than dna0, else returns 0 }"
    );

}
int seedDNA()
{
    //create a random seed dna
       //create random leader dna
    // generate random dna vector on the host
    std::vector<float> host_vector(1000000);
    std::generate(host_vector.begin(), host_vector.end(), rand);

    // create vector on the device
    compute::vector<float> device_vector(1000000, ctx);

    // copy data to the device
    compute::copy(
        host_vector.begin(),
        host_vector.end(),
        device_vector.begin(),
        queue
    );

}
int compareDNA(DNA0,DNA1)
{
    //compare DNA0 to DNA1 to find changed polygons
    boost::compute::function<int (int)> compareDNA =
    boost::compute::make_function_from_source<int (int)>(
        "compareDNA",
        "int compareDNA(int x) { return x + 4; }"
    );
}
int compareimage(image0,image1)
{
    //compare two raster images, return 1 if image1 fitter than image0, else return 0
    boost::compute::function<int (int)> compareDNA =
    boost::compute::make_function_from_source<int (int)>(
        "compareimage",
        "int compareimage(int image0, int image1) { return x + 4; }"
    );
}

int renderDNA (DNA, boundx0, boundy0, boundx1, boundy1)
{
	//render input DNA to a raster image
 boost::compute::function<int (int)> renderDNA =
    boost::compute::make_function_from_source<int (int)>(
        "renderDNA",
        "int renderDNA(int x) { //for each shape in dna
    {
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, gl_texture_);

    glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex2f(0, 0);
    glTexCoord2f(0, 1); glVertex2f(0, h);
    glTexCoord2f(1, 1); glVertex2f(w, h);
    glTexCoord2f(1, 0); glVertex2f(w, 0);
    glEnd();
    } }"
    );
}

int renderSVG (DNA, boundx0, boundy0, boundx1, boundy1)
{
    //render input DNA to a vector image in an opengl texture
 boost::compute::function<int (int)> renderSVG =
    boost::compute::make_function_from_source<int (int)>(
        "renderSVG",
        "int renderSVG(int x) {

        //for each shape in dna
    {
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, gl_texture_);

    glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex2f(0, 0);
    glTexCoord2f(0, 1); glVertex2f(0, h);
    glTexCoord2f(1, 1); glVertex2f(w, h);
    glTexCoord2f(1, 0); glVertex2f(w, 0);
    glEnd();
    } }"
    );
}

}

int mutateDNA (DNA)
{
     //mutate dna
    boost::compute::function<int (int)> mutateDNA =
    boost::compute::make_function_from_source<int (int)>(
        "mutateDNA",
        "int mutateDNA(int DNA) { //mutate input DNA randomly
        mutated_shape = RANDINT(NUM_SHAPES);
    double roulette = RANDDOUBLE(2.8);
    double drastic = RANDDOUBLE(2);

    // mutate color
    if(roulette<1)
    {
        if(dna_test[mutated_shape].a < 0.01 // completely transparent shapes are stupid
                || roulette<0.25)
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].a += RANDDOUBLE(0.1);
                dna_test[mutated_shape].a = CLAMP(dna_test[mutated_shape].a, 0.0, 1.0);
            }
            else
                dna_test[mutated_shape].a = RANDDOUBLE(1.0);
        }
        else if(roulette<0.50)
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].r += RANDDOUBLE(0.1);
                dna_test[mutated_shape].r = CLAMP(dna_test[mutated_shape].r, 0.0, 1.0);
            }
            else
                dna_test[mutated_shape].r = RANDDOUBLE(1.0);
        }
        else if(roulette<0.75)
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].g += RANDDOUBLE(0.1);
                dna_test[mutated_shape].g = CLAMP(dna_test[mutated_shape].g, 0.0, 1.0);
            }
            else
                dna_test[mutated_shape].g = RANDDOUBLE(1.0);
        }
        else
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].b += RANDDOUBLE(0.1);
                dna_test[mutated_shape].b = CLAMP(dna_test[mutated_shape].b, 0.0, 1.0);
            }
            else
                dna_test[mutated_shape].b = RANDDOUBLE(1.0);
        }
    }

    // mutate shape
    else if(roulette < 2.0)
    {
        int point_i = RANDINT(NUM_POINTS);
        if(roulette<1.5)
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].points[point_i].x += (int)RANDDOUBLE(WIDTH/10.0);
                dna_test[mutated_shape].points[point_i].x = CLAMP(dna_test[mutated_shape].points[point_i].x, 0, WIDTH-1);
            }
            else
                dna_test[mutated_shape].points[point_i].x = RANDDOUBLE(WIDTH);
        }
        else
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].points[point_i].y += (int)RANDDOUBLE(HEIGHT/10.0);
                dna_test[mutated_shape].points[point_i].y = CLAMP(dna_test[mutated_shape].points[point_i].y, 0, HEIGHT-1);
            }
            else
                dna_test[mutated_shape].points[point_i].y = RANDDOUBLE(HEIGHT);
        }
    }

    // mutate stacking
    else
    {
        int destination = RANDINT(NUM_SHAPES);
        shape_t s = dna_test[mutated_shape];
        dna_test[mutated_shape] = dna_test[destination];
        dna_test[destination] = s;
        return destination;
    }
    return -1;
 }"
    );

}

int saveDNA(DNA)
{
	int result;

	while(1)
	{
		// start by writing a temp file.

		pFile = fopen ("volution.dna.temp","w");
		fprintf (pFile, DNA);
		fclose (pFile);

		// Then rename the real backup to a secondary backup.

		result = rename("volution.dna","volution_2.dna");

		// Then rename the temp file to the primary backup

		result = rename("volution.dna.temp","volution.dna");

		// Then delete the temp file

		result = remove("volution.dna.temp");

	}
}

int saverender(DNA)
{
    //render DNA and save resulting image to disk as .svg file and raster image (.png)

    //render image from DNA
    renderDNA(DNA);
    //save resultant image to disk as svg and png files
}

int importimage(image)
{
    //import specified image into the gpu memory
    // create vector on the device
    compute::vector<float> device_vector(1000000, ctx);
     //load image into gpu memory
    // copy data to the device
    compute::copy(
        host_vector.begin(),
        host_vector.end(),
        device_vector.begin(),
        queue
    );
}

int drawshape()
{
	//user draws shape from ui

    //start drawing shape vertex by vertex
    //until max number of vertices reached or user closes polygon by clicking on initial vertex

    //check if drawn shape gives a better fitness

    //if it does update the leaderDNA
}

int dragvertex()
{
	//user drags vertex from ui

    //user stops dragging vertex

    //check if dragged vertex improves fitness

    //if it does update the leaderDNA
}
<commit_msg>tidying<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#include <vexcl/vexcl.hpp>

#include <boost/compute.hpp>

#include <algorithm>
#include <QtGui>
#include <QtOpenGL>
#include <boost/compute/command_queue.hpp>
#include <boost/compute/kernel.hpp>
#include <boost/compute/program.hpp>
#include <boost/compute/source.hpp>
#include <boost/compute/system.hpp>
#include <boost/compute/interop/opengl.hpp>

using namespace std;
namespace compute = boost::compute;

int main (int argc, char* argv[])
{
	//set some default values for when no commandline arguments are given
	int accuracy = 90;
	int polygons = 50;
	int vertices = 6;
    //read input commandline arguments
    for (int i = 1; i < argc; ++i)
    {
        if (std::string(argv[i]) == "-a")
            {
                //initialise desired accuracy variable according to commandline argument -a
                accuracy = ;

            }
        if (std::string(argv[i]) == "-p")
            {
                //initialise maximum polygons variable according to commandline argument -p
                polygons = ;

            }
        if (std::string(argv[i]) == "-v")
            {
                //initialise maximum verices per polygon variable according to commandline argument -v
                vertices = ;

            }
    }
     // get the default compute device
    compute::device gpu = compute::system::default_device();

    // create a compute context and command queue
    compute::context ctx(gpu);
    compute::command_queue queue(ctx, gpu);

    //initialise variables in gpu
    const size_t n = 1024 * 1024;
    compute::vector<float> leaderDNA(ctx, n);
    compute::vector<float> mutatedDNA(ctx, n);
    compute::vector<float> leaderDNArender(ctx, n);
    compute::vector<float> mutatedDNArender(ctx, n);
    compute::vector<float> originalimage(ctx, n);

    //load image into gpu memory
    if (std::string(argv[i]) == "")
            {
                //load file according to commandline argument into gpu vector
                compute::vector<float> originalimage(ctx, n);
            }
    // copy data to the device
    compute::copy(
        host_vector.begin(),
        host_vector.end(),
        device_vector.begin(),
        queue
    );

    //initialise variables
	class DNA
	{
		public:
		string genome;
        int polygons;
        int vertices;
        polygon[polygons];

	}
    class polygon;
    {
        public:
        int x[vertices];
        int y[vertices];
        int R;
        int G;
        int B;
        int alpha;
    }

    //initialise DNA with a random seed
    leaderDNA = seedDNA();
    //run render loop until desired accuracy is reached
    while (leaderaccuracy<accuracy)
        {
            //mutate from the leaderDNA
            mutatedDNA = mutateDNA(leaderDNA)
            //compute fitness of mutation vs leaderDNA
            //check if it is fitter, if so overwrite leaderDNA
            if (computefitness(leaderDNA,mutatedDNA) == 1)
            {
                //overwrite leaderDNA
                leaderDNA = mutatedDNA;
            }
            //compute accuracy percent
            computefitnesspercent(leaderDNA, originalimage)
        }
    //perform final render, output svg and raster image
    saverender(leaderDNA);
}
int computefitnesspercent (DNA, originalimage)
{
    //compute what % match DNA is to original image
     boost::compute::function<int (int)> computefitnesspercent =
    boost::compute::make_function_from_source<int (int)>(
        "computefitnesspercent",
        "int computefitnesspercent(int x) { //read leader dna

    //compare input dna to leader dna to find changed polygons
    compareDNA(leaderDNA,DNA);
    //create bounding box containing changed polygons

    //render leader dna within bounding box
    leaderrender = renderDNA(leaderDNA,boundx,boundy);
    //render input dna within bounding box
    inputrender = renderDNA(DNA,boundx,boundy);
    //compare leader and input dna rendered bounding boxes
    compareimage(leaderrender,inputrender);
    //returns % match }"
    );
}
int computefitness (DNA0, DNA1)
{
	//compute the fitness of input DNA, i.e. how close is it to original image?
  boost::compute::function<int (int)> computefitness =
    boost::compute::make_function_from_source<int (int)>(
        "computefitness",
        "int computefitness(int x) { //read leader dna

    //compare input dna to leader dna to find changed polygons
    compareDNA(leaderDNA,DNA);
    //create bounding box containing changed polygons

    //render leader dna within bounding box
    leaderrender = renderDNA(leaderDNA,boundx,boundy);
    //render input dna within bounding box
    inputrender = renderDNA(DNA,boundx,boundy);
    //compare leader and input dna rendered bounding boxes
    compareimage(leaderrender,inputrender);
    //returns 1 if dna1 is fitter than dna0, else returns 0 }"
    );

}
int seedDNA()
{
    //create a random seed dna
       //create random leader dna
    // generate random dna vector on the host
    std::vector<float> host_vector(1000000);
    std::generate(host_vector.begin(), host_vector.end(), rand);

    // create vector on the device
    compute::vector<float> device_vector(1000000, ctx);

    // copy data to the device
    compute::copy(
        host_vector.begin(),
        host_vector.end(),
        device_vector.begin(),
        queue
    );

}
int compareDNA(DNA0,DNA1)
{
    //compare DNA0 to DNA1 to find changed polygons
    boost::compute::function<int (int)> compareDNA =
    boost::compute::make_function_from_source<int (int)>(
        "compareDNA",
        "int compareDNA(int x) { return x + 4; }"
    );
}
int compareimage(image0,image1)
{
    //compare two raster images, return 1 if image1 fitter than image0, else return 0
    boost::compute::function<int (int)> compareDNA =
    boost::compute::make_function_from_source<int (int)>(
        "compareimage",
        "int compareimage(int image0, int image1) { return x + 4; }"
    );
}

int renderDNA (DNA, boundx0, boundy0, boundx1, boundy1)
{
	//render input DNA to a raster image
 boost::compute::function<int (int)> renderDNA =
    boost::compute::make_function_from_source<int (int)>(
        "renderDNA",
        "int renderDNA(int x) { //for each shape in dna
    {
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, gl_texture_);

    glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex2f(0, 0);
    glTexCoord2f(0, 1); glVertex2f(0, h);
    glTexCoord2f(1, 1); glVertex2f(w, h);
    glTexCoord2f(1, 0); glVertex2f(w, 0);
    glEnd();
    } }"
    );
}

int renderSVG (DNA, boundx0, boundy0, boundx1, boundy1)
{
    //render input DNA to a vector image in an opengl texture
 boost::compute::function<int (int)> renderSVG =
    boost::compute::make_function_from_source<int (int)>(
        "renderSVG",
        "int renderSVG(int x) {

        //for each shape in dna
    {
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, gl_texture_);

    glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex2f(0, 0);
    glTexCoord2f(0, 1); glVertex2f(0, h);
    glTexCoord2f(1, 1); glVertex2f(w, h);
    glTexCoord2f(1, 0); glVertex2f(w, 0);
    glEnd();
    } }"
    );
}

}

int mutateDNA (DNA)
{
     //mutate dna
    boost::compute::function<int (int)> mutateDNA =
    boost::compute::make_function_from_source<int (int)>(
        "mutateDNA",
        "int mutateDNA(int DNA) { //mutate input DNA randomly
        mutated_shape = RANDINT(NUM_SHAPES);
    double roulette = RANDDOUBLE(2.8);
    double drastic = RANDDOUBLE(2);

    // mutate color
    if(roulette<1)
    {
        if(dna_test[mutated_shape].a < 0.01 // completely transparent shapes are stupid
                || roulette<0.25)
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].a += RANDDOUBLE(0.1);
                dna_test[mutated_shape].a = CLAMP(dna_test[mutated_shape].a, 0.0, 1.0);
            }
            else
                dna_test[mutated_shape].a = RANDDOUBLE(1.0);
        }
        else if(roulette<0.50)
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].r += RANDDOUBLE(0.1);
                dna_test[mutated_shape].r = CLAMP(dna_test[mutated_shape].r, 0.0, 1.0);
            }
            else
                dna_test[mutated_shape].r = RANDDOUBLE(1.0);
        }
        else if(roulette<0.75)
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].g += RANDDOUBLE(0.1);
                dna_test[mutated_shape].g = CLAMP(dna_test[mutated_shape].g, 0.0, 1.0);
            }
            else
                dna_test[mutated_shape].g = RANDDOUBLE(1.0);
        }
        else
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].b += RANDDOUBLE(0.1);
                dna_test[mutated_shape].b = CLAMP(dna_test[mutated_shape].b, 0.0, 1.0);
            }
            else
                dna_test[mutated_shape].b = RANDDOUBLE(1.0);
        }
    }

    // mutate shape
    else if(roulette < 2.0)
    {
        int point_i = RANDINT(NUM_POINTS);
        if(roulette<1.5)
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].points[point_i].x += (int)RANDDOUBLE(WIDTH/10.0);
                dna_test[mutated_shape].points[point_i].x = CLAMP(dna_test[mutated_shape].points[point_i].x, 0, WIDTH-1);
            }
            else
                dna_test[mutated_shape].points[point_i].x = RANDDOUBLE(WIDTH);
        }
        else
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].points[point_i].y += (int)RANDDOUBLE(HEIGHT/10.0);
                dna_test[mutated_shape].points[point_i].y = CLAMP(dna_test[mutated_shape].points[point_i].y, 0, HEIGHT-1);
            }
            else
                dna_test[mutated_shape].points[point_i].y = RANDDOUBLE(HEIGHT);
        }
    }

    // mutate stacking
    else
    {
        int destination = RANDINT(NUM_SHAPES);
        shape_t s = dna_test[mutated_shape];
        dna_test[mutated_shape] = dna_test[destination];
        dna_test[destination] = s;
        return destination;
    }
    return -1;
 }"
    );

}

int saveDNA(DNA)
{
	int result;

	while(1)
	{
		// start by writing a temp file.

		pFile = fopen ("volution.dna.temp","w");
		fprintf (pFile, DNA);
		fclose (pFile);

		// Then rename the real backup to a secondary backup.

		result = rename("volution.dna","volution_2.dna");

		// Then rename the temp file to the primary backup

		result = rename("volution.dna.temp","volution.dna");

		// Then delete the temp file

		result = remove("volution.dna.temp");

	}
}

int saverender(DNA)
{
    //render DNA and save resulting image to disk as .svg file and raster image (.png)

    //render image from DNA
    renderDNA(DNA);
    //save resultant image to disk as svg and png files
}

int importimage(image)
{
    //import specified image into the gpu memory
    // create vector on the device
    compute::vector<float> originalimage(1000000, ctx);
     //load image into gpu memory
    // copy data to the device
    compute::copy(
        host_vector.begin(),
        host_vector.end(),
        device_vector.begin(),
        queue
    );
}

int drawshape()
{
	//user draws shape from ui

    //start drawing shape vertex by vertex
    //until max number of vertices reached or user closes polygon by clicking on initial vertex

    //check if drawn shape gives a better fitness

    //if it does update the leaderDNA
}

int dragvertex()
{
	//user drags vertex from ui

    //user stops dragging vertex

    //check if dragged vertex improves fitness

    //if it does update the leaderDNA
}
<|endoftext|>


<commit_before>/*
This file is part of cphVB and copyright (c) 2012 the cphVB team:
http://cphvb.bitbucket.org

cphVB is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.

cphVB is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the
GNU Lesser General Public License along with cphVB.

If not, see <http://www.gnu.org/licenses/>.
*/

#include <cassert>
#include <cstring>
#include <iostream>
#include <cphvb.h>

#include "cphvb_vem_node.h"

//Function pointers to the VE.
static cphvb_init ve_init;
static cphvb_execute ve_execute;
static cphvb_shutdown ve_shutdown;
static cphvb_reg_func ve_reg_func;

//The VE components
static cphvb_component **vem_node_components;

//Our self
static cphvb_component *vem_node_myself;

//Number of user-defined functions registered.
static cphvb_intp userfunc_count = 0;

/* Initialize the VEM
 *
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_init(cphvb_component *self)
{
    cphvb_intp children_count;
    cphvb_error err;
    vem_node_myself = self;

    err = cphvb_component_children(self, &children_count, &vem_node_components);
    if (children_count != 1)
    {
		std::cerr << "Unexpected number of child nodes for VEM, must be 1" << std::endl;
		return CPHVB_ERROR;
    }

    if (err != CPHVB_SUCCESS)
	    return err;

    ve_init = vem_node_components[0]->init;
    ve_execute = vem_node_components[0]->execute;
    ve_shutdown = vem_node_components[0]->shutdown;
    ve_reg_func = vem_node_components[0]->reg_func;

    //Let us initiate the simple VE and register what it supports.
    if((err = ve_init(vem_node_components[0])) != 0)
        return err;

    return CPHVB_SUCCESS;
}

/* Shutdown the VEM, which include a instruction flush
 *
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_shutdown(void)
{
    cphvb_error err;
    err = ve_shutdown();
    cphvb_component_free(vem_node_components[0]);//Only got one child.
    ve_init     = NULL;
    ve_execute  = NULL;
    ve_shutdown = NULL;
    ve_reg_func = NULL;
    cphvb_component_free_ptr(vem_node_components);
    vem_node_components = NULL;
    return err;
}

/* Register a new user-defined function.
 *
 * @lib Name of the shared library e.g. libmyfunc.so
 *      When NULL the default library is used.
 * @fun Name of the function e.g. myfunc
 * @id Identifier for the new function. The bridge should set the
 *     initial value to Zero. (in/out-put)
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_reg_func(char *fun, cphvb_intp *id)
{
	cphvb_error e;

    if(*id == 0)//Only if parent didn't set the ID.
        *id = ++userfunc_count;

    if((e = ve_reg_func(fun, id)) != CPHVB_SUCCESS)
    {
        *id = 0;
        return e;
    }
    return e;
}

/* Execute a list of instructions (blocking, for the time being).
 * It is required that the VEM supports all instructions in the list.
 *
 * @instruction A list of instructions to execute
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_execute(cphvb_intp count,
                                   cphvb_instruction inst_list[])
{
    if (count <= 0)
        return CPHVB_SUCCESS;

    #ifdef CPHVB_TRACE
        cphvb_intp i;
        for(i=0; i<count; ++i)
        {
            cphvb_instruction* inst = &inst_list[i];
            cphvb_component_trace_inst(vem_node_myself, inst);
        }
    #endif

   // cphvb_pprint_instr_list(inst_list, count, "NODE");

    return ve_execute(count, inst_list);
}
<commit_msg>The VEM-NODE will now report if not all arrays were discarded on exit.<commit_after>/*
This file is part of cphVB and copyright (c) 2012 the cphVB team:
http://cphvb.bitbucket.org

cphVB is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.

cphVB is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the
GNU Lesser General Public License along with cphVB.

If not, see <http://www.gnu.org/licenses/>.
*/

#include <cassert>
#include <cstring>
#include <iostream>
#include <cphvb.h>
#include <set>

#include "cphvb_vem_node.h"

//Function pointers to the VE.
static cphvb_init ve_init;
static cphvb_execute ve_execute;
static cphvb_shutdown ve_shutdown;
static cphvb_reg_func ve_reg_func;

//The VE components
static cphvb_component **vem_node_components;

//Our self
static cphvb_component *vem_node_myself;

//Number of user-defined functions registered.
static cphvb_intp userfunc_count = 0;

//Allocated arrays
static std::set<cphvb_array*> allocated_arys;

/* Initialize the VEM
 *
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_init(cphvb_component *self)
{
    cphvb_intp children_count;
    cphvb_error err;
    vem_node_myself = self;

    err = cphvb_component_children(self, &children_count, &vem_node_components);
    if (children_count != 1)
    {
		std::cerr << "Unexpected number of child nodes for VEM, must be 1" << std::endl;
		return CPHVB_ERROR;
    }

    if (err != CPHVB_SUCCESS)
	    return err;

    ve_init = vem_node_components[0]->init;
    ve_execute = vem_node_components[0]->execute;
    ve_shutdown = vem_node_components[0]->shutdown;
    ve_reg_func = vem_node_components[0]->reg_func;

    //Let us initiate the simple VE and register what it supports.
    if((err = ve_init(vem_node_components[0])) != 0)
        return err;

    return CPHVB_SUCCESS;
}

/* Shutdown the VEM, which include a instruction flush
 *
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_shutdown(void)
{
    cphvb_error err;
    err = ve_shutdown();
    cphvb_component_free(vem_node_components[0]);//Only got one child.
    ve_init     = NULL;
    ve_execute  = NULL;
    ve_shutdown = NULL;
    ve_reg_func = NULL;
    cphvb_component_free_ptr(vem_node_components);
    vem_node_components = NULL;

    if(allocated_arys.size() > 0)
    {
        fprintf(stderr, "[NODE-VEM] Warning %ld arrays were "
                "not discarded on exit.\n", (long) allocated_arys.size());
    }
    return err;
}

/* Register a new user-defined function.
 *
 * @lib Name of the shared library e.g. libmyfunc.so
 *      When NULL the default library is used.
 * @fun Name of the function e.g. myfunc
 * @id Identifier for the new function. The bridge should set the
 *     initial value to Zero. (in/out-put)
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_reg_func(char *fun, cphvb_intp *id)
{
	cphvb_error e;

    if(*id == 0)//Only if parent didn't set the ID.
        *id = ++userfunc_count;

    if((e = ve_reg_func(fun, id)) != CPHVB_SUCCESS)
    {
        *id = 0;
        return e;
    }
    return e;
}

/* Execute a list of instructions (blocking, for the time being).
 * It is required that the VEM supports all instructions in the list.
 *
 * @instruction A list of instructions to execute
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_execute(cphvb_intp count,
                                   cphvb_instruction inst_list[])
{
    if (count <= 0)
        return CPHVB_SUCCESS;

    for(cphvb_intp i=0; i<count; ++i)
    {
        cphvb_instruction* inst = &inst_list[i];
        #ifdef CPHVB_TRACE
            cphvb_component_trace_inst(vem_node_myself, inst);
        #endif
        int nop = cphvb_operands_in_instruction(inst);
        cphvb_array **operands = cphvb_inst_operands(inst);

        //Save all new arrays
        for(cphvb_intp o=0; o<nop; ++o)
            allocated_arys.insert(operands[o]);

        //And remove discared arrays
        if(inst->opcode == CPHVB_DISCARD)
        {
            if(allocated_arys.erase(operands[0]) != 1)
                fprintf(stderr, "[NODE-VEM] discarding unknown array\n");
        }
    }

   // cphvb_pprint_instr_list(inst_list, count, "NODE");

    return ve_execute(count, inst_list);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <gtest/gtest.h>
#include <teelogging/teelogging.h>
#include "../pipeline.h"
#include "../channel.h"

class PipelineTest : testing::Test { };

TEST(PipelineTest, Test_fibonacci_n4134)
{
	/*
	// n4134: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4134.pdf
	generator<int> fib(int n)
	{
		int a = 0;
		int b = 1;
		while (n-- > 0)
		{
			yield a;
			auto next = a + b;
			a = b;
			b = next;
		}
	}
	*/

	auto fib = [](int n_) {
		return cu::pull_type<int>(
			[&](cu::push_type<int>& yield) {
				int n = n_;
				int a = 0;
				int b = 1;
				while (n-- > 0)
				{
					yield (a);
					auto next = a + b;
					a = b;
					b = next;
				}
			}
		);
	};
	for (auto& v : fib(233))
	{
		std::cout << v << std::endl;
		if (v > 10)
			break;
	}
}

auto range(int stop)
{
	return cu::pull_type<int>(
		[&](auto& yield) {
			for(int i=0;i<stop;++i)
				yield(i);
		}
	);
}

auto range(int start, int stop, int step=1)
{
	return cu::pull_type<int>(
		[&](auto& yield) {
			for(int i=start;i<stop;stop+=step)
				yield(i);
		}
	);
}

TEST(PipelineTest, Test_range_simple)
{
	LOGI("range simple");
	for (auto v : range(100))
		LOGI(-> "%d", v);
	for (auto v : range(10, 100, 2))
		LOGI("-> %d", v);
}

TEST(PipelineTest, Test_recursive_n4134)
{
	std::function<cu::pull_type<int>(int,int)> range_rec = [&range_rec](int a_, int b_) -> cu::pull_type<int> {
		return cu::pull_type<int>(
			[&](auto& yield) {
				int a = a_;
				int b = b_;
				/////////////////////
				auto n = b - a;
				if (n <= 0)
					return;
				if (n == 1)
				{
					yield (a);
					return;
				}

				auto mid = a + n / 2;

				// original proposal is:
				//     yield range(a, mid)
				//     yield range(mid, b)

				for (auto i : range_rec(a, mid))
					yield (i);
				for (auto i : range_rec(mid, b))
					yield (i);
				///////////////////////
			}
		);
	};

	LOGI("range recursive");
	for (auto v : range_rec(1, 10))
		LOGI("%d", v);
}

TEST(PipelineTest, Test3)
{
	auto fib = [](int n) {
		return cu::push_type<int>(
			[&](cu::pull_type<int>& source) {
				for (auto& s : source)
				{
					LOGI("<fib(%d)> received: %d", n, s);
				}
			}
		);
	};
	auto fib20 = fib(20);
	fib20(1);
	fib20(3);
	fib20(7);
}

<commit_msg>Update test_coroutine.cpp<commit_after>#include <iostream>
#include <gtest/gtest.h>
#include <teelogging/teelogging.h>
#include "../pipeline.h"
#include "../channel.h"

class PipelineTest : testing::Test { };

TEST(PipelineTest, Test_fibonacci_n4134)
{
	/*
	// n4134: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4134.pdf
	generator<int> fib(int n)
	{
		int a = 0;
		int b = 1;
		while (n-- > 0)
		{
			yield a;
			auto next = a + b;
			a = b;
			b = next;
		}
	}
	*/

	auto fib = [](int n_) {
		return cu::pull_type<int>(
			[&](cu::push_type<int>& yield) {
				int n = n_;
				int a = 0;
				int b = 1;
				while (n-- > 0)
				{
					yield (a);
					auto next = a + b;
					a = b;
					b = next;
				}
			}
		);
	};
	for (auto& v : fib(233))
	{
		std::cout << v << std::endl;
		if (v > 10)
			break;
	}
}

auto range(int stop)
{
	return cu::pull_type<int>(
		[&](auto& yield) {
			for(int i=0;i<stop;++i)
				yield(i);
		}
	);
}

auto range(int start, int stop, int step=1)
{
	return cu::pull_type<int>(
		[&](auto& yield) {
			for(int i=start;i<stop;stop+=step)
				yield(i);
		}
	);
}

TEST(PipelineTest, Test_range_simple)
{
	LOGI("range simple");
	for (auto v : range(100))
		LOGI("-> %d", v);
	for (auto v : range(10, 100, 2))
		LOGI("-> %d", v);
}

TEST(PipelineTest, Test_recursive_n4134)
{
	std::function<cu::pull_type<int>(int,int)> range_rec = [&range_rec](int a_, int b_) -> cu::pull_type<int> {
		return cu::pull_type<int>(
			[&](auto& yield) {
				int a = a_;
				int b = b_;
				/////////////////////
				auto n = b - a;
				if (n <= 0)
					return;
				if (n == 1)
				{
					yield (a);
					return;
				}

				auto mid = a + n / 2;

				// original proposal is:
				//     yield range(a, mid)
				//     yield range(mid, b)

				for (auto i : range_rec(a, mid))
					yield (i);
				for (auto i : range_rec(mid, b))
					yield (i);
				///////////////////////
			}
		);
	};

	LOGI("range recursive");
	for (auto v : range_rec(1, 10))
		LOGI("%d", v);
}

TEST(PipelineTest, Test3)
{
	auto fib = [](int n) {
		return cu::push_type<int>(
			[&](cu::pull_type<int>& source) {
				for (auto& s : source)
				{
					LOGI("<fib(%d)> received: %d", n, s);
				}
			}
		);
	};
	auto fib20 = fib(20);
	fib20(1);
	fib20(3);
	fib20(7);
}

<|endoftext|>


<commit_before>/**
 * Copyright (C) 2015 Virgil Security Inc.
 *
 * Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com>
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     (1) Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *     (2) Redistributions 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.
 *
 *     (3) Neither the name of the copyright holder nor the names of its
 *     contributors may be used to endorse or promote products derived from
 *     this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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.
 */

#include <fstream>
#include <stdexcept>
#include <string>

#include <tclap/CmdLine.h>

#include <virgil/crypto/VirgilByteArray.h>

#include <cli/version.h>
#include <cli/config.h>
#include <cli/pair.h>
#include <cli/util.h>

#ifdef SPLIT_CLI
#define MAIN main
#else
#define MAIN public_key_get_main
#endif

int MAIN(int argc, char **argv) {
    try {
      std::string description =
            "Get Virgil Public Key from the Virgil Keys service.\n";

        std::vector <std::string> examples;
        examples.push_back(
                "Get pure Virgil Public Key:\n"
                "virgil public-key-get -o virgil_pub.key -e email:user@domain.com\n"
                );

        examples.push_back(
                "Get Virgil Public Key with associated user data:\n"
                "virgil public-key-get -o virgil_pub.key -e email:user@domain.com -k private.key\n"
                );

        std::string descriptionMessage = virgil::cli::getDescriptionMessage(description, examples);

        // Parse arguments.
        TCLAP::CmdLine cmd(descriptionMessage, ' ', virgil::cli_version());

        TCLAP::ValueArg<std::string> outArg("o", "out", "Output Virgil Public Key. If omitted stdout is used.",
                false, "", "file");

        TCLAP::ValueArg<std::string> publicKeyIdArg("e", "public-key-id",
                "Virgil Public Key identifier, associated with given Private Key.\n"
                "Format:\n"
                "[id|vkey|email]:<value>\n"
                "where:\n"
                "\t* if id, then <value> - UUID associated with Public Key;\n"
                "\t* if vkey, then <value> - user's Virgil Public Key file stored locally;\n"
                "\t* if email, then <value> - user email associated with Public Key.\n",
                true, "", "arg");

        TCLAP::ValueArg<std::string> privateKeyArg("k", "key", "Private Key. If specified then all"
                " user data associated with Virgil Public Key will be provided.",
                false , "", "file");

        TCLAP::ValueArg<std::string> privatePasswordArg("p", "key-pwd", "Private Key password.",
                false, "", "arg");

        cmd.add(privatePasswordArg);
        cmd.add(privateKeyArg);
        cmd.add(publicKeyIdArg);
        cmd.add(outArg);
        cmd.parse(argc, argv);

    } catch (TCLAP::ArgException& exception) {
        std::cerr << "public-key-get. Error: " << exception.error() << " for arg " << exception.argId() << std::endl;
        return EXIT_FAILURE;
    } catch (std::exception& exception) {
        std::cerr << "public-key-get. Error: " << exception.what() << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
<commit_msg>Add public-key-get<commit_after>/**
 * Copyright (C) 2015 Virgil Security Inc.
 *
 * Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com>
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     (1) Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *     (2) Redistributions 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.
 *
 *     (3) Neither the name of the copyright holder nor the names of its
 *     contributors may be used to endorse or promote products derived from
 *     this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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.
 */

#include <iostream>
#include <stdexcept>
#include <string>

#include <tclap/CmdLine.h>

#include <virgil/sdk/ServicesHub.h>
#include <virgil/sdk/io/Marshaller.h>

#include <cli/version.h>
#include <cli/config.h>
#include <cli/pair.h>
#include <cli/util.h>

namespace vsdk = virgil::sdk;
namespace vcrypto = virgil::crypto;
namespace vcli = virgil::cli;

#ifdef SPLIT_CLI
#define MAIN main
#else
#define MAIN public_key_get_main
#endif

int MAIN(int argc, char **argv) {
    try {
      std::string description =
            "Get Virgil Public Key from the Virgil Keys service.\n";

        std::vector <std::string> examples;
        examples.push_back(
                "Get Virgil Public Key:\n"
                "virgil public-key-get -o public.vkey -e <public_key_id> \n");

        std::string descriptionMessage = virgil::cli::getDescriptionMessage(description, examples);

        // Parse arguments.
        TCLAP::CmdLine cmd(descriptionMessage, ' ', virgil::cli_version());

        TCLAP::ValueArg<std::string> outArg("o", "out", "Virgil Public Key. If omitted stdout is used.",
                false, "", "file");

        TCLAP::ValueArg<std::string> publicKeyIdArg("e", "public-key-id", "Public Key identifier\n",
                true, "", "arg");

        cmd.add(publicKeyIdArg);
        cmd.add(outArg);
        cmd.parse(argc, argv);

        vsdk::ServicesHub servicesHub(VIRGIL_ACCESS_TOKEN);
        std::string publicKeyId = publicKeyIdArg.getValue();

        vsdk::model::PublicKey publicKey = servicesHub.publicKey().get(publicKeyId);
        std::string publicKeyStr = vsdk::io::Marshaller<vsdk::model::PublicKey>::toJson<4>(publicKey);
        vcli::writeBytes(outArg.getValue(), publicKeyStr);

    } catch (TCLAP::ArgException& exception) {
        std::cerr << "public-key-get. Error: " << exception.error() << " for arg " << exception.argId() << std::endl;
        return EXIT_FAILURE;
    } catch (std::exception& exception) {
        std::cerr << "public-key-get. Error: " << exception.what() << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
<|endoftext|>