<commit_before>#include "pass_bits/analyser/openmp.hpp"
#include "pass_bits/problem/space_mission/gtoc1.hpp"
#include "pass_bits/problem/optimisation_benchmark/de_jong_function.hpp"
#include "pass_bits/helper/evaluation_time_stall.hpp"
#include "pass_bits/optimiser/parallel_swarm_search.hpp"
#include "pass_bits/optimiser/particle_swarm_optimisation.hpp"
#include "pass_bits/analyser/problem_evaluation_time.hpp"
#include "pass_bits/helper/regression.hpp"
#include "pass_bits/helper/random.hpp"
#include <unistd.h>

bool pass::enable_openmp(const pass::problem &problem)
{
  // Output information
  std::cout << " =========================== Start openMP Analyse ========================= " << std::endl;
  std::cout << "                                                                            " << std::endl;
  std::cout << " Your Problem:                " << problem.name << std::endl;
  std::cout << " Dimension:                   " << problem.dimension() << std::endl;
  std::cout << " Number Threads:              " << pass::number_of_threads() << std::endl;
  std::cout << " Maximum Speedup:             " << pass::number_of_threads() << std::endl;
  std::cout << "                                                                            " << std::endl;

  std::cout << " ============================= Start Evaluation =========================== " << std::endl;

  double your_time = pass::problem_evaluation_time(problem);

  std::cout << "                                                                            " << std::endl;
  std::cout << " Evaluation time: " << your_time * 1e-6 << " milliseconds." << std::endl;
  std::cout << "                                                                            " << std::endl;
  std::cout << " ============================= End Evaluation  ============================ " << std::endl;
  std::cout << "                                                                            " << std::endl;

  arma::mat summary;
  arma::rowvec model;

  // Check if the file exists
  bool ok = model.load("./openmp_model.pass");

  if (ok == false)
  {
    std::cout << " - Model does not exist                                                     " << std::endl;
    std::cout << "                                                                            " << std::endl;
    // Start training the data
    summary = train(30);
    model = build_model(summary);
  }
  else
  {
    std::cout << "                                                                            " << std::endl;
    std::cout << " - Model exists                                                             " << std::endl;
    std::cout << "                                                                            " << std::endl;
  }

  std::cout << " ========================= Start SpeedUp Prediction ======================= " << std::endl;

  // Generating a regression object
  pass::regression r;

  if (model.n_elem == 3)
  {
    double predict_linear = r.predict_linear(your_time, model);

    if (predict_linear > 0.9 * pass::number_of_threads())
    {
      predict_linear = 0.9 * pass::number_of_threads();
    }
    std::cout << "                                                                            " << std::endl;
    std::cout << " Your speedUp would be approximately: " << predict_linear << std::endl;

    std::cout << "                                                                            " << std::endl;
    std::cout << " ========================== Done SpeedUp Prediction ======================= " << std::endl;

    if (predict_linear > pass::number_of_threads() / 2) // efficienty is more than 50 %
    {
      std::cout << "                                                                            " << std::endl;
      std::cout << " You should activate openMP!                                                " << std::endl;
      std::cout << "                                                                            " << std::endl;
      std::cout << " =========================  Done openMP Analyse  ========================== " << std::endl;
      return true;
    }
    if (predict_linear < 1) // is efficienty is more than 50 %
    {
      std::cout << "                                                                            " << std::endl;
      std::cout << " You should NOT activate openMP!                                            " << std::endl;
      std::cout << "                                                                            " << std::endl;
      std::cout << " =========================  Done openMP Analyse  ========================== " << std::endl;
      return false;
    }
    if (predict_linear > 1 && predict_linear < pass::number_of_threads() / 2) // efficienty is less than 50 %
    {
      std::cout << "                                                                            " << std::endl;
      std::cout << " You should decide yourself if to activate openMP or not!                   " << std::endl;
      std::cout << "                                                                            " << std::endl;
    }
  }
  else
  {
    double predict_poly = r.predict_poly(your_time, model);

    if (predict_poly > 0.9 * pass::number_of_threads())
    {
      predict_poly = 0.9 * pass::number_of_threads();
    }
    std::cout << "                                                                            " << std::endl;
    std::cout << " Your speedUp would be approximately: " << predict_poly << std::endl;
    std::cout << "                                                                            " << std::endl;
    std::cout << " ========================== Done SpeedUp Prediction ======================= " << std::endl;

    if (predict_poly > pass::number_of_threads() / 2) // is efficienty is more than 50 %
    {
      std::cout << "                                                                            " << std::endl;
      std::cout << " You should activate openMP!                                                " << std::endl;
      std::cout << "                                                                            " << std::endl;
      std::cout << " =========================  Done openMP Analyse  ========================== " << std::endl;
      return true;
    }
    if (predict_poly < 1) // is efficienty is more than 50 %
    {
      std::cout << "                                                                            " << std::endl;
      std::cout << " You should NOT activate openMP!                                            " << std::endl;
      std::cout << "                                                                            " << std::endl;
      std::cout << " =========================  Done openMP Analyse  ========================== " << std::endl;
      return false;
    }
    if (predict_poly > 1 && predict_poly < pass::number_of_threads() / 2) // is efficienty is more than 50 %
    {
      std::cout << "                                                                            " << std::endl;
      std::cout << " You should decide yourself if to activate openMP or not!                   " << std::endl;
      std::cout << "                                                                            " << std::endl;
    }
  }

  std::cout << "                                                                            " << std::endl;
  std::cout << " =========================  Done openMP Analyse  ========================== " << std::endl;

  return true;
}

arma::mat pass::train(const int &examples)
{
  // set random seed
  arma::arma_rng::set_seed_random();

  // define the maximum of runs
  arma::uword alg_runs = 2;

  // Array including all alg runtime, we want to test
  //std::array<int, 30> repetitions = {1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 14, 15, 17, 20, 25, 28, 30, 33, 36,
  //                                   40, 45, 50, 60, 70, 80, 100, 120, 140, 160};

  arma::rowvec repetitions = pass::integers_uniform_in_range(50, 200, examples);

  // Output information
  std::cout << " ============================= Start Trainining =========================== " << std::endl;
  std::cout << "                                                                            " << std::endl;

  arma::vec serial(alg_runs);
  arma::vec parallel(alg_runs);

  arma::mat summary(2, repetitions.size());

  std::srand(time(0));
  int count = 0;

  pass::particle_swarm_optimisation algorithm_serial;
  algorithm_serial.maximal_evaluations = 2000;

  pass::parallel_swarm_search algorithm_parallel;
  algorithm_parallel.maximal_evaluations = 2000;

  for (auto repetition : repetitions)
  {
    std::cout << "Repetition " << repetition << std::endl;
    // Problem initialisation
    pass::gtoc1 test_problem;
    pass::evaluation_time_stall simulated_problem(test_problem);
    simulated_problem.repetitions = repetition;

    double ev_time = pass::problem_evaluation_time(simulated_problem);
    summary(0, count) = ev_time;

    // Do the evaluation for serial and parallel for all the evaluations values
    for (arma::uword serial_run = 0; serial_run < alg_runs; ++serial_run)
    {
      //algorithm_serial.maximal_duration = std::chrono::seconds(5);
      auto serial_alg = algorithm_serial.optimise(simulated_problem);
      //serial(serial_run) = serial_alg.evaluations;
      serial(serial_run) = serial_alg.duration.count();
      //usleep(1000000);
    }

    for (arma::uword parallel_run = 0; parallel_run < alg_runs; ++parallel_run)
    {
      //algorithm_parallel.maximal_duration = std::chrono::seconds(5);
      auto parallel_alg = algorithm_parallel.optimise(simulated_problem);
      //parallel(parallel_run) = parallel_alg.evaluations;
      parallel(parallel_run) = parallel_alg.duration.count();
      //usleep(1000000);
    }

    summary(1, count) = arma::mean(parallel) / arma::mean(serial);

    std::cout << "Summary: \n"
              << summary.col(count) << std::endl;

    count++;

    // load bar

    double temp_count = static_cast<double>(examples) / static_cast<double>(count);
    std::cout << " \r " << 100.0 / temp_count << " % completed." << std::flush;
  }

  std::cout << std::endl
            << std::endl
            << " Training completed successfully.\n"
            << std::flush;
  std::cout << "                                                                            " << std::endl;
  std::cout << " ===========================  End Training  =============================== " << std::endl;
  std::cout << "                                                                            " << std::endl;

  return summary;
}

arma::rowvec pass::build_model(const arma::mat &training_points)
{
  // File to save the model
  std::string file_name;
  file_name = "openmp_model.pass";

  // Generating a regression object
  pass::regression r;

  // Getting the data for the model
  arma::rowvec x_values = training_points.row(0);
  arma::rowvec y_values = training_points.row(1);

  // Output information
  std::cout << " =========================== Start Building Models ======================== " << std::endl;
  std::cout << "                                                                            " << std::endl;
  std::cout << " Building linear model for the training data.                               " << std::endl;
  std::cout << "                                                                            " << std::endl;

  // Generating the linear model

  arma::rowvec linear_model = r.linear_model(x_values, y_values);

  if (linear_model(2) >= 0.9)
  {
    std::cout << " Finished building linear model.                                            " << std::endl;
    std::cout << "                                                                            " << std::endl;
    std::cout << " Linear Model is suitable.                                                  " << std::endl;
    std::cout << "                                                                            " << std::endl;
    std::cout << " ========================= Done Building Models  ========================== " << std::endl;
    std::cout << "                                                                            " << std::endl;

    linear_model.save("./" + file_name, arma::raw_ascii);

    return linear_model;
  }

  std::cout << " Finished building linear model.                                            " << std::endl;
  std::cout << "                                                                            " << std::endl;
  std::cout << " Linear Model is NOT suitable.                                              " << std::endl;
  std::cout << "                                                                            " << std::endl;
  std::cout << " Building polynomial model for the training data.                           " << std::endl;
  std::cout << "                                                                            " << std::endl;

  arma::rowvec poly_model = r.poly_model(x_values, y_values, 3);
  std::cout << " ========================= Done Building Models  ========================== " << std::endl;
  std::cout << "                                                                            " << std::endl;

  poly_model.save("./" + file_name, arma::raw_ascii);

  return poly_model;
}
<commit_msg>tests<commit_after>#include "pass_bits/analyser/openmp.hpp"
#include "pass_bits/problem/space_mission/gtoc1.hpp"
#include "pass_bits/problem/optimisation_benchmark/de_jong_function.hpp"
#include "pass_bits/helper/evaluation_time_stall.hpp"
#include "pass_bits/optimiser/parallel_swarm_search.hpp"
#include "pass_bits/optimiser/particle_swarm_optimisation.hpp"
#include "pass_bits/analyser/problem_evaluation_time.hpp"
#include "pass_bits/helper/regression.hpp"
#include "pass_bits/helper/random.hpp"
#include <unistd.h>

bool pass::enable_openmp(const pass::problem &problem)
{
  // Output information
  std::cout << " =========================== Start openMP Analyse ========================= " << std::endl;
  std::cout << "                                                                            " << std::endl;
  std::cout << " Your Problem:                " << problem.name << std::endl;
  std::cout << " Dimension:                   " << problem.dimension() << std::endl;
  std::cout << " Number Threads:              " << pass::number_of_threads() << std::endl;
  std::cout << " Maximum Speedup:             " << pass::number_of_threads() << std::endl;
  std::cout << "                                                                            " << std::endl;

  std::cout << " ============================= Start Evaluation =========================== " << std::endl;

  double your_time = pass::problem_evaluation_time(problem);

  std::cout << "                                                                            " << std::endl;
  std::cout << " Evaluation time: " << your_time * 1e-6 << " milliseconds." << std::endl;
  std::cout << "                                                                            " << std::endl;
  std::cout << " ============================= End Evaluation  ============================ " << std::endl;
  std::cout << "                                                                            " << std::endl;

  arma::mat summary;
  arma::rowvec model;

  // Check if the file exists
  bool ok = model.load("./openmp_model.pass");

  if (ok == false)
  {
    std::cout << " - Model does not exist                                                     " << std::endl;
    std::cout << "                                                                            " << std::endl;
    // Start training the data
    summary = train(30);
    model = build_model(summary);
  }
  else
  {
    std::cout << "                                                                            " << std::endl;
    std::cout << " - Model exists                                                             " << std::endl;
    std::cout << "                                                                            " << std::endl;
  }

  std::cout << " ========================= Start SpeedUp Prediction ======================= " << std::endl;

  // Generating a regression object
  pass::regression r;

  if (model.n_elem == 3)
  {
    double predict_linear = r.predict_linear(your_time, model);

    if (predict_linear > 0.9 * pass::number_of_threads())
    {
      predict_linear = 0.9 * pass::number_of_threads();
    }
    std::cout << "                                                                            " << std::endl;
    std::cout << " Your speedUp would be approximately: " << predict_linear << std::endl;

    std::cout << "                                                                            " << std::endl;
    std::cout << " ========================== Done SpeedUp Prediction ======================= " << std::endl;

    if (predict_linear > pass::number_of_threads() / 2) // efficienty is more than 50 %
    {
      std::cout << "                                                                            " << std::endl;
      std::cout << " You should activate openMP!                                                " << std::endl;
      std::cout << "                                                                            " << std::endl;
      std::cout << " =========================  Done openMP Analyse  ========================== " << std::endl;
      return true;
    }
    if (predict_linear < 1) // is efficienty is more than 50 %
    {
      std::cout << "                                                                            " << std::endl;
      std::cout << " You should NOT activate openMP!                                            " << std::endl;
      std::cout << "                                                                            " << std::endl;
      std::cout << " =========================  Done openMP Analyse  ========================== " << std::endl;
      return false;
    }
    if (predict_linear > 1 && predict_linear < pass::number_of_threads() / 2) // efficienty is less than 50 %
    {
      std::cout << "                                                                            " << std::endl;
      std::cout << " You should decide yourself if to activate openMP or not!                   " << std::endl;
      std::cout << "                                                                            " << std::endl;
    }
  }
  else
  {
    double predict_poly = r.predict_poly(your_time, model);

    if (predict_poly > 0.9 * pass::number_of_threads())
    {
      predict_poly = 0.9 * pass::number_of_threads();
    }
    std::cout << "                                                                            " << std::endl;
    std::cout << " Your speedUp would be approximately: " << predict_poly << std::endl;
    std::cout << "                                                                            " << std::endl;
    std::cout << " ========================== Done SpeedUp Prediction ======================= " << std::endl;

    if (predict_poly > pass::number_of_threads() / 2) // is efficienty is more than 50 %
    {
      std::cout << "                                                                            " << std::endl;
      std::cout << " You should activate openMP!                                                " << std::endl;
      std::cout << "                                                                            " << std::endl;
      std::cout << " =========================  Done openMP Analyse  ========================== " << std::endl;
      return true;
    }
    if (predict_poly < 1) // is efficienty is more than 50 %
    {
      std::cout << "                                                                            " << std::endl;
      std::cout << " You should NOT activate openMP!                                            " << std::endl;
      std::cout << "                                                                            " << std::endl;
      std::cout << " =========================  Done openMP Analyse  ========================== " << std::endl;
      return false;
    }
    if (predict_poly > 1 && predict_poly < pass::number_of_threads() / 2) // is efficienty is more than 50 %
    {
      std::cout << "                                                                            " << std::endl;
      std::cout << " You should decide yourself if to activate openMP or not!                   " << std::endl;
      std::cout << "                                                                            " << std::endl;
    }
  }

  std::cout << "                                                                            " << std::endl;
  std::cout << " =========================  Done openMP Analyse  ========================== " << std::endl;

  return true;
}

arma::mat pass::train(const int &examples)
{
  // set random seed
  arma::arma_rng::set_seed_random();

  // define the maximum of runs
  arma::uword alg_runs = 2;

  // Array including all alg runtime, we want to test
  //std::array<int, 30> repetitions = {1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 14, 15, 17, 20, 25, 28, 30, 33, 36,
  //                                   40, 45, 50, 60, 70, 80, 100, 120, 140, 160};

  arma::rowvec repetitions = pass::integers_uniform_in_range(50, 200, examples);

  // Output information
  std::cout << " ============================= Start Trainining =========================== " << std::endl;
  std::cout << "                                                                            " << std::endl;

  arma::vec serial(alg_runs);
  arma::vec parallel(alg_runs);

  arma::mat summary(2, repetitions.size());

  std::srand(time(0));
  int count = 0;

  pass::particle_swarm_optimisation algorithm_serial;
  algorithm_serial.maximal_duration = std::chrono::seconds(5);

  pass::parallel_swarm_search algorithm_parallel;
  algorithm_serial.maximal_duration = std::chrono::seconds(5);

  for (auto repetition : repetitions)
  {
    std::cout << "Repetition " << repetition << std::endl;
    // Problem initialisation
    pass::gtoc1 test_problem;
    pass::evaluation_time_stall simulated_problem(test_problem);
    simulated_problem.repetitions = repetition;

    double ev_time = pass::problem_evaluation_time(simulated_problem);
    summary(0, count) = ev_time;

    // Do the evaluation for serial and parallel for all the evaluations values
    for (arma::uword serial_run = 0; serial_run < alg_runs; ++serial_run)
    {

      auto serial_alg = algorithm_serial.optimise(simulated_problem);
      serial(serial_run) = serial_alg.evaluations;
      usleep(1000000);
    }

    for (arma::uword parallel_run = 0; parallel_run < alg_runs; ++parallel_run)
    {
      auto parallel_alg = algorithm_parallel.optimise(simulated_problem);
      parallel(parallel_run) = parallel_alg.evaluations;
      usleep(1000000);
    }

    summary(1, count) = arma::mean(parallel) / arma::mean(serial);

    std::cout << "Summary: \n"
              << summary.col(count) << std::endl;

    count++;

    // load bar

    double temp_count = static_cast<double>(examples) / static_cast<double>(count);
    std::cout << " \r " << 100.0 / temp_count << " % completed." << std::flush;
  }

  std::cout << std::endl
            << std::endl
            << " Training completed successfully.\n"
            << std::flush;
  std::cout << "                                                                            " << std::endl;
  std::cout << " ===========================  End Training  =============================== " << std::endl;
  std::cout << "                                                                            " << std::endl;

  return summary;
}

arma::rowvec pass::build_model(const arma::mat &training_points)
{
  // File to save the model
  std::string file_name;
  file_name = "openmp_model.pass";

  // Generating a regression object
  pass::regression r;

  // Getting the data for the model
  arma::rowvec x_values = training_points.row(0);
  arma::rowvec y_values = training_points.row(1);

  // Output information
  std::cout << " =========================== Start Building Models ======================== " << std::endl;
  std::cout << "                                                                            " << std::endl;
  std::cout << " Building linear model for the training data.                               " << std::endl;
  std::cout << "                                                                            " << std::endl;

  // Generating the linear model

  arma::rowvec linear_model = r.linear_model(x_values, y_values);

  if (linear_model(2) >= 0.9)
  {
    std::cout << " Finished building linear model.                                            " << std::endl;
    std::cout << "                                                                            " << std::endl;
    std::cout << " Linear Model is suitable.                                                  " << std::endl;
    std::cout << "                                                                            " << std::endl;
    std::cout << " ========================= Done Building Models  ========================== " << std::endl;
    std::cout << "                                                                            " << std::endl;

    linear_model.save("./" + file_name, arma::raw_ascii);

    return linear_model;
  }

  std::cout << " Finished building linear model.                                            " << std::endl;
  std::cout << "                                                                            " << std::endl;
  std::cout << " Linear Model is NOT suitable.                                              " << std::endl;
  std::cout << "                                                                            " << std::endl;
  std::cout << " Building polynomial model for the training data.                           " << std::endl;
  std::cout << "                                                                            " << std::endl;

  arma::rowvec poly_model = r.poly_model(x_values, y_values, 3);
  std::cout << " ========================= Done Building Models  ========================== " << std::endl;
  std::cout << "                                                                            " << std::endl;

  poly_model.save("./" + file_name, arma::raw_ascii);

  return poly_model;
}
<|endoftext|>


<commit_before>/*

        Basic Spout sender for Cinder

        Search for "SPOUT" to see what is required
        Uses the Spout dll

        Based on the RotatingBox CINDER example without much modification
        Nothing fancy about this, just the basics.

        Search for "SPOUT" to see what is required

    ==========================================================================
    Copyright (C) 2014 Lynn Jarvis.

    This program 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.

    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 Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    ==========================================================================

*/

#include "cinder/app/AppNative.h"
#include "cinder/ImageIo.h"
#include "cinder/gl/Texture.h"
#include "cinder/Camera.h"
#include "cinder/Utilities.h"
#include "cinder/ImageIo.h"
#include "cinder/Surface.h"
#include "cinder/System.h"
#include "cinder/Capture.h"
#include "cinder/gl/Fbo.h"
#include "cinder/MayaCamUI.h"
#include "cinder/ip/EdgeDetect.h"
#include "cinder/ip/Blend.h"
#include "cinder/params/Params.h"

#include <vector>

// spout
#include "spout.h"

using namespace ci;
using namespace ci::app;
using namespace std;
using namespace ci::gl;

class ReymentaRuttEtraApp : public AppNative {
public:
    void prepareSettings(Settings *settings);
	void setup();
	void update();
	void draw();
    void shutdown();
	void mouseDown(MouseEvent event);
	void mouseDrag(MouseEvent event);

private:
    // -------- SPOUT -------------
    SpoutSender spoutsender;                    // Create a Spout sender object
    bool bInitialized;                          // true if a sender initializes OK
    bool bMemoryMode;                           // tells us if texture share compatible
    unsigned int g_Width, g_Height;             // size of the texture being sent out
    char SenderName[256];                       // sender name
    gl::Texture spoutTexture;                   // Local Cinder texture used for sharing
    // RuttEtra
	Capture mInput;
	gl::Texture webcam;
	vector <Vec3f> pixData;

	CameraPersp mCam;
	MayaCamUI maya;
	int stepX, stepY, lineBreak;
	int blackBreak;
	float elevation;
	bool enableSobel, enableWebcamPreview, enableGrayScale;
	Surface8u edge;
	string pos;
	params::InterfaceGl mParams;

};

// -------- SPOUT -------------
void ReymentaRuttEtraApp::prepareSettings(Settings *settings)
{
        g_Width  = 640;
        g_Height = 512;
        settings->setWindowSize( g_Width, g_Height );
        settings->setFullScreen( false );
        settings->setResizable( false ); // keep the screen size constant for a sender
        settings->setFrameRate( 60.0f );
}
// ----------------------------

void ReymentaRuttEtraApp::setup()
{
    glEnable( GL_TEXTURE_2D );
    gl::enableDepthRead();
    gl::enableDepthWrite();

    // -------- SPOUT -------------
    // Set up the texture we will use to send out
    // We grab the screen so it has to be the same size
    spoutTexture =  gl::Texture(g_Width, g_Height);
    strcpy_s(SenderName, "Reymenta RuttEtra Sender"); // we have to set a sender name first
    // Optionally test for texture share compatibility
    // bMemoryMode informs us whether Spout initialized for texture share or memory share
    bMemoryMode = spoutsender.GetMemoryShareMode();
    // Initialize a sender
    bInitialized = spoutsender.CreateSender(SenderName, g_Width, g_Height);
    // RuttEtra
	elevation = 10;
	enableWebcamPreview = enableSobel = false;
	enableGrayScale = true;

	mCam.setPerspective(45.0, getWindowAspectRatio(), 0.1f, 10000.0f);
	mCam.lookAt(Vec3f(0.0, 0.0, 500.0), Vec3f::zero(), Vec3f::yAxis());
	mCam.setCenterOfInterestPoint(Vec3f::zero());

	maya.setCurrentCam(mCam);
	try {
		mInput = Capture(640, 480);
		mInput.start();
	}
	catch (...) {
		console() << "Failed to initialize capture" << std::endl;
	}

	for (int i = 0; i < mInput.getWidth()*mInput.getHeight(); i++)
	{
		pixData.push_back(Vec3f::zero());
	}
	stepY = 5;
	stepX = 5;
	blackBreak = 64;
	mParams = params::InterfaceGl("Rutt-Etra", Vec2i(225, 200));
	mParams.addParam("Elevation damping", &elevation, "min=1 max=10 step=0.01");
	mParams.addParam("Steps X", &stepX, "min=1 max=10");
	mParams.addParam("StepsY", &stepY, "min=1 max=10");
	mParams.addParam("BlackBreak", &blackBreak, "min=0 max=255");

	mParams.addSeparator();
	mParams.addParam("Enable preview", &enableWebcamPreview);
	mParams.addParam("Enable sobel", &enableSobel);
	mParams.addParam("Enable grayscale", &enableGrayScale);

	edge = Surface8u(mInput.getWidth(), mInput.getHeight(), false, SurfaceChannelOrder::RGB);

}
void ReymentaRuttEtraApp::mouseDown(MouseEvent event){
	maya.mouseDown(event.getPos());

}
void ReymentaRuttEtraApp::mouseDrag(MouseEvent event){
	bool middle = event.isMiddleDown() || (event.isMetaDown() && event.isLeftDown());
	bool right = event.isRightDown() || (event.isControlDown() && event.isLeftDown());
	maya.mouseDrag(event.getPos(), event.isLeftDown() && !middle && !right, middle, right);
	pos = toString(event.getPos().x) + "-" + toString(event.getPos().y);
}
void ReymentaRuttEtraApp::update()
{
	if (mInput.isCapturing())
	{
		if (enableSobel)
		{
			ci::ip::edgeDetectSobel(mInput.getSurface(), &edge);
			if (enableWebcamPreview) webcam = gl::Texture(edge);

		}
		else
		{
			if (enableWebcamPreview) webcam = gl::Texture(mInput.getSurface());
		}

		Surface::Iter surfIter = enableSobel ? surfIter = edge.getIter(edge.getBounds()) : surfIter = mInput.getSurface().getIter(mInput.getBounds());

		int p = 0;
		while (surfIter.line())
		{
			while (surfIter.pixel())
			{
				float brightness = surfIter.r() + surfIter.g() + surfIter.b();

				if (surfIter.x() % stepX == 0 && surfIter.y() % stepY == 0)
				{
					pixData[p].set(surfIter.x(), surfIter.mWidth - surfIter.y(), brightness / elevation); // !!!inversion
					p++;
				}

			}
		}

		lineBreak = p;
	}
}

void ReymentaRuttEtraApp::draw()
{
    gl::clear( Color( 0.39f, 0.025f, 0.0f ) ); // red/brown to be different

	gl::color(Color::white());
	gl::disableDepthRead();
	if (enableWebcamPreview) gl::draw(webcam, webcam.getBounds(), getWindowBounds());
	gl::enableDepthWrite();
	gl::enableDepthRead(true);
	gl::pushMatrices();
	gl::setMatrices(maya.getCamera());
	gl::color(Color::black());
	int drawnVertices = 0;
	gl::begin(GL_LINE_STRIP);
	int lb = 0;
	for (int x = 0; x < lineBreak; x++)
	{
		if (x < pixData.size())
		{
			if (x > 0)
			{

				if (pixData[x].z < blackBreak / (elevation / 3) || (pixData[x].x < pixData[x - 1].x && x != 0))
				{
					gl::end();
					gl::begin(GL_LINE_STRIP);

				}
				else{
					gl::vertex(pixData[x]);
					gl::color(enableGrayScale ? Color::gray(pixData[x].z / (255 * 3) * elevation) : Color::white());
					drawnVertices++;
				}
			}
		}
	}

	gl::end();

	gl::popMatrices();
	gl::enableAlphaBlending();
	gl::drawString("pos : " + pos + "Points : " + toString(lineBreak) + "\n Drawn Vertices:" + toString(drawnVertices), Vec2f(getWindowWidth() - 120, 20), Color::black());
	gl::disableAlphaBlending();
    // -------- SPOUT -------------
    if(bInitialized) {

        // Grab the screen (current read buffer) into the local spout texture
        spoutTexture.bind();
        glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, g_Width, g_Height);
        spoutTexture.unbind();

        // Send the texture for all receivers to use
        // NOTE : if SendTexture is called with a framebuffer object bound, that binding will be lost
        // and has to be restored afterwards because Spout uses an fbo for intermediate rendering
        spoutsender.SendTexture(spoutTexture.getId(), spoutTexture.getTarget(), g_Width, g_Height);

    }

    // Show the user what it is sending
    char txt[256];
    sprintf_s(txt, "Sending as [%s]", SenderName);
    gl::setMatricesWindow( getWindowSize() );
    gl::enableAlphaBlending();
    gl::drawString( txt, Vec2f( toPixels( 20 ), toPixels( 20 ) ), Color( 1, 1, 1 ), Font( "Verdana", toPixels( 24 ) ) );
    sprintf_s(txt, "fps : %2.2d", (int)getAverageFps());
    gl::drawString( txt, Vec2f(getWindowWidth() - toPixels( 100 ), toPixels( 20 ) ), Color( 1, 1, 1 ), Font( "Verdana", toPixels( 24 ) ) );
    gl::disableAlphaBlending();
    // ----------------------------
	mParams.draw();

}
// -------- SPOUT -------------
void ReymentaRuttEtraApp::shutdown()
{
    spoutsender.ReleaseSender();
}
// This line tells Cinder to actually create the application
CINDER_APP_NATIVE( ReymentaRuttEtraApp, RendererGl )
<commit_msg>cam position<commit_after>/*

        Basic Spout sender for Cinder

        Search for "SPOUT" to see what is required
        Uses the Spout dll

        Based on the RotatingBox CINDER example without much modification
        Nothing fancy about this, just the basics.

        Search for "SPOUT" to see what is required

    ==========================================================================
    Copyright (C) 2014 Lynn Jarvis.

    This program 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.

    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 Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    ==========================================================================

*/

#include "cinder/app/AppNative.h"
#include "cinder/ImageIo.h"
#include "cinder/gl/Texture.h"
#include "cinder/Camera.h"
#include "cinder/Utilities.h"
#include "cinder/ImageIo.h"
#include "cinder/Surface.h"
#include "cinder/System.h"
#include "cinder/Capture.h"
#include "cinder/gl/Fbo.h"
#include "cinder/MayaCamUI.h"
#include "cinder/ip/EdgeDetect.h"
#include "cinder/ip/Blend.h"
#include "cinder/params/Params.h"

#include <vector>

// spout
#include "spout.h"

using namespace ci;
using namespace ci::app;
using namespace std;
using namespace ci::gl;

class ReymentaRuttEtraApp : public AppNative {
public:
    void prepareSettings(Settings *settings);
	void setup();
	void update();
	void draw();
    void shutdown();
	void mouseDown(MouseEvent event);
	void mouseDrag(MouseEvent event);

private:
    // -------- SPOUT -------------
    SpoutSender spoutsender;                    // Create a Spout sender object
    bool bInitialized;                          // true if a sender initializes OK
    bool bMemoryMode;                           // tells us if texture share compatible
    unsigned int g_Width, g_Height;             // size of the texture being sent out
    char SenderName[256];                       // sender name
    gl::Texture spoutTexture;                   // Local Cinder texture used for sharing
    // RuttEtra
	Capture mInput;
	gl::Texture webcam;
	vector <Vec3f> pixData;

	CameraPersp mCam;
	MayaCamUI maya;
	int stepX, stepY, lineBreak;
	int blackBreak;
	float elevation;
	bool enableSobel, enableWebcamPreview, enableGrayScale;
	Surface8u edge;
	string pos;
	params::InterfaceGl mParams;

};

// -------- SPOUT -------------
void ReymentaRuttEtraApp::prepareSettings(Settings *settings)
{
        g_Width  = 640;
        g_Height = 480;
        settings->setWindowSize( g_Width, g_Height );
        settings->setFullScreen( false );
        settings->setResizable( false ); // keep the screen size constant for a sender
        settings->setFrameRate( 60.0f );
}
// ----------------------------

void ReymentaRuttEtraApp::setup()
{
    glEnable( GL_TEXTURE_2D );
    gl::enableDepthRead();
    gl::enableDepthWrite();

    // -------- SPOUT -------------
    // Set up the texture we will use to send out
    // We grab the screen so it has to be the same size
    spoutTexture =  gl::Texture(g_Width, g_Height);
    strcpy_s(SenderName, "Reymenta RuttEtra Sender"); // we have to set a sender name first
    // Optionally test for texture share compatibility
    // bMemoryMode informs us whether Spout initialized for texture share or memory share
    bMemoryMode = spoutsender.GetMemoryShareMode();
    // Initialize a sender
    bInitialized = spoutsender.CreateSender(SenderName, g_Width, g_Height);
    // RuttEtra
	elevation = 10;
	enableWebcamPreview = enableSobel = false;
	enableGrayScale = true;

	mCam.setPerspective(45.0, getWindowAspectRatio(), 0.1f, 10000.0f);
	//mCam.lookAt(Vec3f(0.0, 0.0, 500.0), Vec3f::zero(), Vec3f::yAxis());
	mCam.lookAt(Vec3f(320.0, 240.0, 500.0), Vec3f(320.0, 240.0, 0.0), Vec3f::yAxis());
	//mCam.setCenterOfInterestPoint(Vec3f::zero());
	mCam.setCenterOfInterestPoint(Vec3f(320.0, 240.0, 0.0));

	maya.setCurrentCam(mCam);
	try {
		mInput = Capture(640, 480);
		mInput.start();
	}
	catch (...) {
		console() << "Failed to initialize capture" << std::endl;
	}

	for (int i = 0; i < mInput.getWidth()*mInput.getHeight(); i++)
	{
		pixData.push_back(Vec3f::zero());
	}
	stepY = 5;
	stepX = 5;
	blackBreak = 64;
	mParams = params::InterfaceGl("Rutt-Etra", Vec2i(225, 200));
	mParams.addParam("Elevation damping", &elevation, "min=1 max=10 step=0.01");
	mParams.addParam("Steps X", &stepX, "min=1 max=10");
	mParams.addParam("StepsY", &stepY, "min=1 max=10");
	mParams.addParam("BlackBreak", &blackBreak, "min=0 max=255");

	mParams.addSeparator();
	mParams.addParam("Enable preview", &enableWebcamPreview);
	mParams.addParam("Enable sobel", &enableSobel);
	mParams.addParam("Enable grayscale", &enableGrayScale);

	edge = Surface8u(mInput.getWidth(), mInput.getHeight(), false, SurfaceChannelOrder::RGB);

}
void ReymentaRuttEtraApp::mouseDown(MouseEvent event){
	maya.mouseDown(event.getPos());

}
void ReymentaRuttEtraApp::mouseDrag(MouseEvent event){
	bool middle = event.isMiddleDown() || (event.isMetaDown() && event.isLeftDown());
	bool right = event.isRightDown() || (event.isControlDown() && event.isLeftDown());
	maya.mouseDrag(event.getPos(), event.isLeftDown() && !middle && !right, middle, right);
	pos = toString(event.getPos().x) + "-" + toString(event.getPos().y);
}
void ReymentaRuttEtraApp::update()
{
	if (mInput.isCapturing())
	{
		if (enableSobel)
		{
			ci::ip::edgeDetectSobel(mInput.getSurface(), &edge);
			if (enableWebcamPreview) webcam = gl::Texture(edge);

		}
		else
		{
			if (enableWebcamPreview) webcam = gl::Texture(mInput.getSurface());
		}

		Surface::Iter surfIter = enableSobel ? surfIter = edge.getIter(edge.getBounds()) : surfIter = mInput.getSurface().getIter(mInput.getBounds());

		int p = 0;
		while (surfIter.line())
		{
			while (surfIter.pixel())
			{
				float brightness = surfIter.r() + surfIter.g() + surfIter.b();

				if (surfIter.x() % stepX == 0 && surfIter.y() % stepY == 0)
				{
					pixData[p].set(surfIter.x(), surfIter.mWidth - surfIter.y(), brightness / elevation); // !!!inversion
					p++;
				}

			}
		}

		lineBreak = p;
	}
}

void ReymentaRuttEtraApp::draw()
{
    gl::clear( Color( 0.39f, 0.025f, 0.0f ) ); // red/brown to be different

	gl::color(Color::white());
	gl::disableDepthRead();
	if (enableWebcamPreview) gl::draw(webcam, webcam.getBounds(), getWindowBounds());
	gl::enableDepthWrite();
	gl::enableDepthRead(true);
	gl::pushMatrices();
	gl::setMatrices(maya.getCamera());
	gl::color(Color::black());
	int drawnVertices = 0;
	gl::begin(GL_LINE_STRIP);
	int lb = 0;
	for (int x = 0; x < lineBreak; x++)
	{
		if (x < pixData.size())
		{
			if (x > 0)
			{

				if (pixData[x].z < blackBreak / (elevation / 3) || (pixData[x].x < pixData[x - 1].x && x != 0))
				{
					gl::end();
					gl::begin(GL_LINE_STRIP);

				}
				else{
					gl::vertex(pixData[x]);
					gl::color(enableGrayScale ? Color::gray(pixData[x].z / (255 * 3) * elevation) : Color::white());
					drawnVertices++;
				}
			}
		}
	}

	gl::end();

	gl::popMatrices();
	gl::enableAlphaBlending();
	gl::drawString("pos : " + pos + "Points : " + toString(lineBreak) + "\n Drawn Vertices:" + toString(drawnVertices), Vec2f(getWindowWidth() - 120, 20), Color::black());
	gl::disableAlphaBlending();
    // -------- SPOUT -------------
    if(bInitialized) {

        // Grab the screen (current read buffer) into the local spout texture
        spoutTexture.bind();
        glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, g_Width, g_Height);
        spoutTexture.unbind();

        // Send the texture for all receivers to use
        // NOTE : if SendTexture is called with a framebuffer object bound, that binding will be lost
        // and has to be restored afterwards because Spout uses an fbo for intermediate rendering
        spoutsender.SendTexture(spoutTexture.getId(), spoutTexture.getTarget(), g_Width, g_Height);

    }

    // Show the user what it is sending
    char txt[256];
    sprintf_s(txt, "Sending as [%s]", SenderName);
    gl::setMatricesWindow( getWindowSize() );
    gl::enableAlphaBlending();
    gl::drawString( txt, Vec2f( toPixels( 20 ), toPixels( 20 ) ), Color( 1, 1, 1 ), Font( "Verdana", toPixels( 24 ) ) );
    sprintf_s(txt, "fps : %2.2d", (int)getAverageFps());
    gl::drawString( txt, Vec2f(getWindowWidth() - toPixels( 100 ), toPixels( 20 ) ), Color( 1, 1, 1 ), Font( "Verdana", toPixels( 24 ) ) );
    gl::disableAlphaBlending();
    // ----------------------------
	mParams.draw();

}
// -------- SPOUT -------------
void ReymentaRuttEtraApp::shutdown()
{
    spoutsender.ReleaseSender();
}
// This line tells Cinder to actually create the application
CINDER_APP_NATIVE( ReymentaRuttEtraApp, RendererGl )
<|endoftext|>


<commit_before>#include "animated_entity.h"

#include <algorithm>

using namespace space_invaders;

AnimatedEntity::AnimatedEntity(Game& game)
  : MovableEntity(game),
    mAnimationStepSize(0),
    mAnimationCounter(0),
    mAnimationFrameIndex(0)
{
  // ...
}

void AnimatedEntity::update(unsigned long dt)
{
  MovableEntity::update(dt);
  if (mCurrentAnimation.size() > 1 && mAnimationStepSize > 0) {
    mAnimationCounter = std::max(0, mAnimationCounter - 1);
    if (mAnimationCounter <= 0) {
      auto nextFrame = ((mAnimationFrameIndex + 1) % mCurrentAnimation.size());
      setAnimationFrame(nextFrame);
      mAnimationCounter = mAnimationStepSize;
    }
  }
}

void AnimatedEntity::setAnimationStepSize(int stepSize)
{
  mAnimationStepSize = stepSize;
  mAnimationCounter = mAnimationStepSize;
}

void AnimatedEntity::setCurrentAnimation(const std::string& name)
{
  if (mAnimations.find(name) != mAnimations.end()) {
    mCurrentAnimation = mAnimations[name];
    mAnimationCounter = mAnimationStepSize;
    setAnimationFrame(0);
  }
}

void AnimatedEntity::setAnimationFrame(unsigned int frameIndex)
{
  if (mCurrentAnimation.empty() == false) {
    // ensure that we are not exceeding animation limits.
    frameIndex = std::min(mCurrentAnimation.size(), frameIndex);

    // get a reference to the next frame dimensions.
    const auto& animationClip = mCurrentAnimation[frameIndex];

    // store current center x and y positions.
    auto centerX = getCenterX();
    auto centerY = getCenterY();

    // assign the new animation frame as the current frame.
    setClip(animationClip);

    // restore center x and y positions.
    setCenterX(centerX);
    setCenterY(centerY);
  }
}

void AnimatedEntity::addAnimationFrame(const std::string& name, const SDL_Rect& rect)
{
  // add a new animation frame container if not yet created.
  if (mAnimations.find(name) == mAnimations.end()) {
    mAnimations[name] = std::vector<SDL_Rect>();
  }

  // add the new animation frame into the container.
  mAnimations[name].push_back(rect);
}<commit_msg>Fixed a bug from the animated entity which did not store the new animation frame index.<commit_after>#include "animated_entity.h"

#include <algorithm>

using namespace space_invaders;

AnimatedEntity::AnimatedEntity(Game& game)
  : MovableEntity(game),
    mAnimationStepSize(0),
    mAnimationCounter(0),
    mAnimationFrameIndex(0)
{
  // ...
}

void AnimatedEntity::update(unsigned long dt)
{
  MovableEntity::update(dt);
  if (mCurrentAnimation.size() > 1 && mAnimationStepSize > 0) {
    mAnimationCounter = std::max(0, mAnimationCounter - 1);
    if (mAnimationCounter <= 0) {
      auto nextFrame = ((mAnimationFrameIndex + 1) % mCurrentAnimation.size());
      setAnimationFrame(nextFrame);
      mAnimationCounter = mAnimationStepSize;
    }
  }
}

void AnimatedEntity::setAnimationStepSize(int stepSize)
{
  mAnimationStepSize = stepSize;
  mAnimationCounter = mAnimationStepSize;
}

void AnimatedEntity::setCurrentAnimation(const std::string& name)
{
  if (mAnimations.find(name) != mAnimations.end()) {
    mCurrentAnimation = mAnimations[name];
    mAnimationCounter = mAnimationStepSize;
    setAnimationFrame(0);
  }
}

void AnimatedEntity::setAnimationFrame(unsigned int frameIndex)
{
  if (mCurrentAnimation.empty() == false) {
    // ensure that we are not exceeding animation limits.
    frameIndex = std::min(mCurrentAnimation.size(), frameIndex);

    // get a reference to the next frame dimensions.
    const auto& animationClip = mCurrentAnimation[frameIndex];

    // store current center x and y positions.
    auto centerX = getCenterX();
    auto centerY = getCenterY();

    // assign the new animation frame as the current frame.
    setClip(animationClip);

    // restore center x and y positions.
    setCenterX(centerX);
    setCenterY(centerY);

    // store the new index.
    mAnimationFrameIndex = frameIndex;
  }
}

void AnimatedEntity::addAnimationFrame(const std::string& name, const SDL_Rect& rect)
{
  // add a new animation frame container if not yet created.
  if (mAnimations.find(name) == mAnimations.end()) {
    mAnimations[name] = std::vector<SDL_Rect>();
  }

  // add the new animation frame into the container.
  mAnimations[name].push_back(rect);
}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2007-2008 The Florida State University
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * 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;
 * neither the name of the copyright holders 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 COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Stephen Hines
 */

#include "arch/arm/isa_traits.hh"
#include "arch/arm/process.hh"
#include "arch/arm/types.hh"
#include "base/loader/elf_object.hh"
#include "base/loader/object_file.hh"
#include "base/misc.hh"
#include "cpu/thread_context.hh"
#include "mem/page_table.hh"
#include "mem/translating_port.hh"
#include "sim/process_impl.hh"
#include "sim/system.hh"

using namespace std;
using namespace ArmISA;

ArmLiveProcess::ArmLiveProcess(LiveProcessParams *params, ObjectFile *objFile)
    : LiveProcess(params, objFile)
{
    stack_base = 0xc0000000L;

    // Set pointer for next thread stack.  Reserve 8M for main stack.
    next_thread_stack_base = stack_base - (8 * 1024 * 1024);

    // Set up break point (Top of Heap)
    brk_point = objFile->dataBase() + objFile->dataSize() + objFile->bssSize();
    brk_point = roundUp(brk_point, VMPageSize);

    // Set up region for mmaps. For now, start at bottom of kuseg space.
    mmap_start = mmap_end = 0x70000000L;
}

void
ArmLiveProcess::startup()
{
    argsInit(MachineBytes, VMPageSize);
}

void
ArmLiveProcess::copyStringArray32(std::vector<std::string> &strings,
        Addr array_ptr, Addr data_ptr,
        TranslatingPort* memPort)
{
    Addr data_ptr_swap;
    for (int i = 0; i < strings.size(); ++i) {
        data_ptr_swap = htog(data_ptr);
        memPort->writeBlob(array_ptr, (uint8_t*)&data_ptr_swap,
                sizeof(uint32_t));
        memPort->writeString(data_ptr, strings[i].c_str());
        array_ptr += sizeof(uint32_t);
        data_ptr += strings[i].size() + 1;
    }
    // add NULL terminator
    data_ptr = 0;

    memPort->writeBlob(array_ptr, (uint8_t*)&data_ptr, sizeof(uint32_t));
}

void
ArmLiveProcess::argsInit(int intSize, int pageSize)
{
    // Overloaded argsInit so that we can fine-tune for ARM architecture
    Process::startup();

    // load object file into target memory
    objFile->loadSections(initVirtMem);

    // Calculate how much space we need for arg & env arrays.
    int argv_array_size = intSize * (argv.size() + 1);
    int envp_array_size = intSize * (envp.size() + 1);
    int arg_data_size = 0;
    for (int i = 0; i < argv.size(); ++i) {
        arg_data_size += argv[i].size() + 1;
    }
    int env_data_size = 0;
    for (int i = 0; i < envp.size(); ++i) {
        env_data_size += envp[i].size() + 1;
    }

    int space_needed =
        argv_array_size + envp_array_size + arg_data_size + env_data_size;
    if (space_needed < 16*1024)
        space_needed = 16*1024;

    // set bottom of stack
    stack_min = stack_base - space_needed;
    // align it
    stack_min = roundDown(stack_min, pageSize);
    stack_size = stack_base - stack_min;
    // map memory
    pTable->allocate(stack_min, roundUp(stack_size, pageSize));

    // map out initial stack contents
    Addr argv_array_base = stack_min + intSize; // room for argc
    Addr envp_array_base = argv_array_base + argv_array_size;
    Addr arg_data_base = envp_array_base + envp_array_size;
    Addr env_data_base = arg_data_base + arg_data_size;

    // write contents to stack
    uint64_t argc = argv.size();
    if (intSize == 8)
        argc = htog((uint64_t)argc);
    else if (intSize == 4)
        argc = htog((uint32_t)argc);
    else
        panic("Unknown int size");

    initVirtMem->writeBlob(stack_min, (uint8_t*)&argc, intSize);

    copyStringArray32(argv, argv_array_base, arg_data_base, initVirtMem);
    copyStringArray32(envp, envp_array_base, env_data_base, initVirtMem);

    /*
    //uint8_t insns[] = {0xe5, 0x9f, 0x00, 0x08, 0xe1, 0xa0, 0xf0, 0x0e};
    uint8_t insns[] = {0x08, 0x00, 0x9f, 0xe5, 0x0e, 0xf0, 0xa0, 0xe1};

    initVirtMem->writeBlob(0xffff0fe0, insns, 8);
    */

    ThreadContext *tc = system->getThreadContext(contextIds[0]);

    tc->setIntReg(ArgumentReg1, argc);
    tc->setIntReg(ArgumentReg2, argv_array_base);
    tc->setIntReg(StackPointerReg, stack_min);

    Addr prog_entry = objFile->entryPoint();
    tc->setPC(prog_entry);
    tc->setNextPC(prog_entry + sizeof(MachInst));
}

ArmISA::IntReg
ArmLiveProcess::getSyscallArg(ThreadContext *tc, int i)
{
    assert(i < 4);
    return tc->readIntReg(ArgumentReg0 + i);
}

void
ArmLiveProcess::setSyscallArg(ThreadContext *tc,
        int i, ArmISA::IntReg val)
{
    assert(i < 4);
    tc->setIntReg(ArgumentReg0 + i, val);
}

void
ArmLiveProcess::setSyscallReturn(ThreadContext *tc,
        SyscallReturn return_value)
{
    tc->setIntReg(ReturnValueReg, return_value.value());
}
<commit_msg>ARM: Set up the initial stack frame to match a recent Linux.<commit_after>/*
 * Copyright (c) 2007-2008 The Florida State University
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * 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;
 * neither the name of the copyright holders 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 COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Stephen Hines
 */

#include "arch/arm/isa_traits.hh"
#include "arch/arm/process.hh"
#include "arch/arm/types.hh"
#include "base/loader/elf_object.hh"
#include "base/loader/object_file.hh"
#include "base/misc.hh"
#include "cpu/thread_context.hh"
#include "mem/page_table.hh"
#include "mem/translating_port.hh"
#include "sim/process_impl.hh"
#include "sim/system.hh"

using namespace std;
using namespace ArmISA;

ArmLiveProcess::ArmLiveProcess(LiveProcessParams *params, ObjectFile *objFile)
    : LiveProcess(params, objFile)
{
    stack_base = 0xbf000000L;

    // Set pointer for next thread stack.  Reserve 8M for main stack.
    next_thread_stack_base = stack_base - (8 * 1024 * 1024);

    // Set up break point (Top of Heap)
    brk_point = objFile->dataBase() + objFile->dataSize() + objFile->bssSize();
    brk_point = roundUp(brk_point, VMPageSize);

    // Set up region for mmaps. For now, start at bottom of kuseg space.
    mmap_start = mmap_end = 0x70000000L;
}

void
ArmLiveProcess::startup()
{
    argsInit(MachineBytes, VMPageSize);
}

void
ArmLiveProcess::copyStringArray32(std::vector<std::string> &strings,
        Addr array_ptr, Addr data_ptr,
        TranslatingPort* memPort)
{
    Addr data_ptr_swap;
    for (int i = 0; i < strings.size(); ++i) {
        data_ptr_swap = htog(data_ptr);
        memPort->writeBlob(array_ptr, (uint8_t*)&data_ptr_swap,
                sizeof(uint32_t));
        memPort->writeString(data_ptr, strings[i].c_str());
        array_ptr += sizeof(uint32_t);
        data_ptr += strings[i].size() + 1;
    }
    // add NULL terminator
    data_ptr = 0;

    memPort->writeBlob(array_ptr, (uint8_t*)&data_ptr, sizeof(uint32_t));
}

void
ArmLiveProcess::argsInit(int intSize, int pageSize)
{
    typedef AuxVector<uint32_t> auxv_t;
    std::vector<auxv_t> auxv;

    string filename;
    if (argv.size() < 1)
        filename = "";
    else
        filename = argv[0];

    //We want 16 byte alignment
    uint64_t align = 16;

    // Overloaded argsInit so that we can fine-tune for ARM architecture
    Process::startup();

    // load object file into target memory
    objFile->loadSections(initVirtMem);

    enum ArmCpuFeature {
        Arm_Swp = 1 << 0,
        Arm_Half = 1 << 1,
        Arm_Thumb = 1 << 2,
        Arm_26Bit = 1 << 3,
        Arm_FastMult = 1 << 4,
        Arm_Fpa = 1 << 5,
        Arm_Vfp = 1 << 6,
        Arm_Edsp = 1 << 7,
        Arm_Java = 1 << 8,
        Arm_Iwmmxt = 1 << 9,
        Arm_Crunch = 1 << 10
    };

    //Setup the auxilliary vectors. These will already have endian conversion.
    //Auxilliary vectors are loaded only for elf formatted executables.
    ElfObject * elfObject = dynamic_cast<ElfObject *>(objFile);
    if (elfObject) {
        uint32_t features =
            Arm_Swp |
            Arm_Half |
            Arm_Thumb |
//            Arm_26Bit |
            Arm_FastMult |
//            Arm_Fpa |
            Arm_Vfp |
            Arm_Edsp |
            Arm_Java |
//            Arm_Iwmmxt |
//            Arm_Crunch |
            0;

        //Bits which describe the system hardware capabilities
        //XXX Figure out what these should be
        auxv.push_back(auxv_t(M5_AT_HWCAP, features));
        //The system page size
        auxv.push_back(auxv_t(M5_AT_PAGESZ, ArmISA::VMPageSize));
        //Frequency at which times() increments
        auxv.push_back(auxv_t(M5_AT_CLKTCK, 0x64));
        // For statically linked executables, this is the virtual address of the
        // program header tables if they appear in the executable image
        auxv.push_back(auxv_t(M5_AT_PHDR, elfObject->programHeaderTable()));
        // This is the size of a program header entry from the elf file.
        auxv.push_back(auxv_t(M5_AT_PHENT, elfObject->programHeaderSize()));
        // This is the number of program headers from the original elf file.
        auxv.push_back(auxv_t(M5_AT_PHNUM, elfObject->programHeaderCount()));
        //This is the address of the elf "interpreter", It should be set
        //to 0 for regular executables. It should be something else
        //(not sure what) for dynamic libraries.
        auxv.push_back(auxv_t(M5_AT_BASE, 0));

        //XXX Figure out what this should be.
        auxv.push_back(auxv_t(M5_AT_FLAGS, 0));
        //The entry point to the program
        auxv.push_back(auxv_t(M5_AT_ENTRY, objFile->entryPoint()));
        //Different user and group IDs
        auxv.push_back(auxv_t(M5_AT_UID, uid()));
        auxv.push_back(auxv_t(M5_AT_EUID, euid()));
        auxv.push_back(auxv_t(M5_AT_GID, gid()));
        auxv.push_back(auxv_t(M5_AT_EGID, egid()));
        //Whether to enable "secure mode" in the executable
        auxv.push_back(auxv_t(M5_AT_SECURE, 0));
        //The filename of the program
        auxv.push_back(auxv_t(M5_AT_EXECFN, 0));
        //The string "v51" with unknown meaning
        auxv.push_back(auxv_t(M5_AT_PLATFORM, 0));
    }

    //Figure out how big the initial stack nedes to be

    // A sentry NULL void pointer at the top of the stack.
    int sentry_size = intSize;

    string platform = "v51";
    int platform_size = platform.size() + 1;

    // The aux vectors are put on the stack in two groups. The first group are
    // the vectors that are generated as the elf is loaded. The second group
    // are the ones that were computed ahead of time and include the platform
    // string.
    int aux_data_size = filename.size() + 1;

    int env_data_size = 0;
    for (int i = 0; i < envp.size(); ++i) {
        env_data_size += envp[i].size() + 1;
    }
    int arg_data_size = 0;
    for (int i = 0; i < argv.size(); ++i) {
        arg_data_size += argv[i].size() + 1;
    }

    int info_block_size =
        sentry_size + env_data_size + arg_data_size +
        aux_data_size + platform_size;

    //Each auxilliary vector is two 4 byte words
    int aux_array_size = intSize * 2 * (auxv.size() + 1);

    int envp_array_size = intSize * (envp.size() + 1);
    int argv_array_size = intSize * (argv.size() + 1);

    int argc_size = intSize;

    //Figure out the size of the contents of the actual initial frame
    int frame_size =
        info_block_size +
        aux_array_size +
        envp_array_size +
        argv_array_size +
        argc_size;

    //There needs to be padding after the auxiliary vector data so that the
    //very bottom of the stack is aligned properly.
    int partial_size = frame_size;
    int aligned_partial_size = roundUp(partial_size, align);
    int aux_padding = aligned_partial_size - partial_size;

    int space_needed = frame_size + aux_padding;

    stack_min = stack_base - space_needed;
    stack_min = roundDown(stack_min, align);
    stack_size = stack_base - stack_min;

    // map memory
    pTable->allocate(roundDown(stack_min, pageSize),
                     roundUp(stack_size, pageSize));

    // map out initial stack contents
    uint32_t sentry_base = stack_base - sentry_size;
    uint32_t aux_data_base = sentry_base - aux_data_size;
    uint32_t env_data_base = aux_data_base - env_data_size;
    uint32_t arg_data_base = env_data_base - arg_data_size;
    uint32_t platform_base = arg_data_base - platform_size;
    uint32_t auxv_array_base = platform_base - aux_array_size - aux_padding;
    uint32_t envp_array_base = auxv_array_base - envp_array_size;
    uint32_t argv_array_base = envp_array_base - argv_array_size;
    uint32_t argc_base = argv_array_base - argc_size;

    DPRINTF(Stack, "The addresses of items on the initial stack:\n");
    DPRINTF(Stack, "0x%x - aux data\n", aux_data_base);
    DPRINTF(Stack, "0x%x - env data\n", env_data_base);
    DPRINTF(Stack, "0x%x - arg data\n", arg_data_base);
    DPRINTF(Stack, "0x%x - platform base\n", platform_base);
    DPRINTF(Stack, "0x%x - auxv array\n", auxv_array_base);
    DPRINTF(Stack, "0x%x - envp array\n", envp_array_base);
    DPRINTF(Stack, "0x%x - argv array\n", argv_array_base);
    DPRINTF(Stack, "0x%x - argc \n", argc_base);
    DPRINTF(Stack, "0x%x - stack min\n", stack_min);

    // write contents to stack

    // figure out argc
    uint32_t argc = argv.size();
    uint32_t guestArgc = ArmISA::htog(argc);

    //Write out the sentry void *
    uint32_t sentry_NULL = 0;
    initVirtMem->writeBlob(sentry_base,
            (uint8_t*)&sentry_NULL, sentry_size);

    //Fix up the aux vectors which point to other data
    for (int i = auxv.size() - 1; i >= 0; i--) {
        if (auxv[i].a_type == M5_AT_PLATFORM) {
            auxv[i].a_val = platform_base;
            initVirtMem->writeString(platform_base, platform.c_str());
        } else if (auxv[i].a_type == M5_AT_EXECFN) {
            auxv[i].a_val = aux_data_base;
            initVirtMem->writeString(aux_data_base, filename.c_str());
        }
    }

    //Copy the aux stuff
    for(int x = 0; x < auxv.size(); x++)
    {
        initVirtMem->writeBlob(auxv_array_base + x * 2 * intSize,
                (uint8_t*)&(auxv[x].a_type), intSize);
        initVirtMem->writeBlob(auxv_array_base + (x * 2 + 1) * intSize,
                (uint8_t*)&(auxv[x].a_val), intSize);
    }
    //Write out the terminating zeroed auxilliary vector
    const uint64_t zero = 0;
    initVirtMem->writeBlob(auxv_array_base + 2 * intSize * auxv.size(),
            (uint8_t*)&zero, 2 * intSize);

    copyStringArray(envp, envp_array_base, env_data_base, initVirtMem);
    copyStringArray(argv, argv_array_base, arg_data_base, initVirtMem);

    initVirtMem->writeBlob(argc_base, (uint8_t*)&guestArgc, intSize);

    ThreadContext *tc = system->getThreadContext(contextIds[0]);
    //Set the stack pointer register
    tc->setIntReg(StackPointerReg, stack_min);
    //A pointer to a function to run when the program exits. We'll set this
    //to zero explicitly to make sure this isn't used.
    tc->setIntReg(ArgumentReg0, 0);
    //Set argument regs 1 and 2 to argv[0] and envp[0] respectively
    if (argv.size() > 0) {
        tc->setIntReg(ArgumentReg1, arg_data_base + arg_data_size -
                                    argv[argv.size() - 1].size() - 1);
    } else {
        tc->setIntReg(ArgumentReg1, 0);
    }
    if (envp.size() > 0) {
        tc->setIntReg(ArgumentReg2, env_data_base + env_data_size -
                                    envp[envp.size() - 1].size() - 1);
    } else {
        tc->setIntReg(ArgumentReg2, 0);
    }

    Addr prog_entry = objFile->entryPoint();
    tc->setPC(prog_entry);
    tc->setNextPC(prog_entry + sizeof(MachInst));

    //Align the "stack_min" to a page boundary.
    stack_min = roundDown(stack_min, pageSize);
}

ArmISA::IntReg
ArmLiveProcess::getSyscallArg(ThreadContext *tc, int i)
{
    assert(i < 4);
    return tc->readIntReg(ArgumentReg0 + i);
}

void
ArmLiveProcess::setSyscallArg(ThreadContext *tc,
        int i, ArmISA::IntReg val)
{
    assert(i < 4);
    tc->setIntReg(ArgumentReg0 + i, val);
}

void
ArmLiveProcess::setSyscallReturn(ThreadContext *tc,
        SyscallReturn return_value)
{
    tc->setIntReg(ReturnValueReg, return_value.value());
}
<|endoftext|>


<commit_before>#include "KeyFrame.h"
#include "LayersMgr.h"
#include "Layer.h"
#include "SpriteUserData.h"

#include <ee/ObjectVector.h>
#include <ee/Exception.h>

#include <easymesh.h>
#include <easyanim.h>
#include <easyparticle3d.h>

#include <sprite2/AnimLerp.h>

#include <algorithm>

namespace eanim
{

KeyFrame::KeyFrame(int time)
	: m_layer(NULL)
{
	m_time = time;
	m_classic_tween = false;
	m_id = 0;
}

KeyFrame::~KeyFrame()
{
	Clear();
}

void KeyFrame::SetLayer(Layer* layer)
{
	cu::RefCountObjAssign(m_layer, layer);
}

void KeyFrame::CopyFromOther(const KeyFrame* src)
{
	if (this == src) {
		return;
	}

	// sprs
	for (size_t i = 0, n = src->m_sprs.size(); i < n; ++i)
	{
		ee::Sprite* s = dynamic_cast<ee::Sprite*>(((cu::Cloneable*)src->m_sprs[i])->Clone());
		SpriteUserData::SetSprData(s, src->m_layer, this);
		m_sprs.push_back(s);

		if (src->m_layer) {
			s->SetObserver(&src->m_layer->GetSpriteObserver());
			src->m_layer->GetSpriteObserver().Insert(s, m_time);
		}
	}

	// skeleton
	m_skeleton.CopyFrom(m_sprs, src->m_skeleton);
	// todo spr's ud
}

void KeyFrame::Insert(ee::Sprite* spr, int idx)
{
	if (!spr) {
		throw ee::Exception("KeyFrame::Insert fail: spr null.");
	}
	spr->AddReference();

	if (m_layer) {
		throw ee::Exception("KeyFrame::Insert: call zz see see.");
	}

	SpriteUserData::SetSprData(spr, m_layer, this);
	ee::ObjectVector<ee::Sprite>::Insert(m_sprs, spr, idx);
	if (m_layer) {
		spr->SetObserver(&m_layer->GetSpriteObserver());
		m_layer->GetSpriteObserver().Insert(spr, m_time);
	}
}

bool KeyFrame::Remove(ee::Sprite* spr)
{
	m_skeleton.RemoveSprite(spr);
	if (m_layer) {
		m_layer->GetSpriteObserver().Remove(spr);
	}

	return ee::ObjectVector<ee::Sprite>::Remove(m_sprs, spr);
}

bool KeyFrame::Reorder(const ee::Sprite* spr, bool up)
{
	return ee::ObjectVector<ee::Sprite>::ResetOrder(m_sprs, spr, up);
}

bool KeyFrame::ReorderMost(const ee::Sprite* spr, bool up)
{
	return ee::ObjectVector<ee::Sprite>::ResetOrderMost(m_sprs, spr, up);
}

bool KeyFrame::Sort(std::vector<ee::Sprite*>& sprs)
{
	return ee::ObjectVector<ee::Sprite>::Sort(m_sprs, sprs);
}

void KeyFrame::Clear()
{
	if (m_layer) {
		for (size_t i = 0, n = m_sprs.size(); i < n; ++i)
			m_layer->GetSpriteObserver().Remove(m_sprs[i]);
	}

	ee::ObjectVector<ee::Sprite>::Clear(m_sprs);
}

void KeyFrame::OnActive()
{
	for (int i = 0, n = m_sprs.size(); i < n; ++i) {
		if (eparticle3d::Sprite* p3d = dynamic_cast<eparticle3d::Sprite*>(m_sprs[i])) {
			if (p3d->IsAlone()) {
				p3d->OnActive();
			}
		}
	}
}

void KeyFrame::GetTweenSprite(const KeyFrame* start, const KeyFrame* end,
							  std::vector<ee::Sprite*>& tween, float process)
{
	// 	// old
	// 	for (int i = 0, n = start->Size(); i < n; ++i)
	// 	{
	// 		ee::Sprite* s = start->m_sprs[i];
	// 		for (int j = 0, m = end->Size(); j < m; ++j) {
	// 			ee::Sprite* e = end->m_sprs[j];
	// 			if (IsTweenMatched(s, e))
	// 			{
	// 				ee::Sprite* mid = s->clone();
	// 				GetTweenSprite(s, e, mid, process);
	// 				tween.push_back(mid);
	// 			}
	// 		}
	// 	}

	SkeletonData &s_skeleton = const_cast<KeyFrame*>(start)->GetSkeletonData(),
		         &e_skeleton = const_cast<KeyFrame*>(end)->GetSkeletonData();
	if (!s_skeleton.Empty() && !e_skeleton.Empty()) {
		SkeletonData::GetTweenSprites(s_skeleton, e_skeleton, tween, process);
	} else {
		std::vector<s2::Sprite*> begins, ends, tweens;
		begins.reserve(start->m_sprs.size());
		copy(start->m_sprs.begin(), start->m_sprs.end(), back_inserter(begins));
		ends.reserve(start->m_sprs.size());
		copy(end->m_sprs.begin(), end->m_sprs.end(), back_inserter(ends));

		s2::AnimLerp::Lerp(begins, ends, tweens, process);

		tween.reserve(tweens.size());
		for (int i = 0, n = tweens.size(); i < n; ++i) {
			tween.push_back(dynamic_cast<ee::Sprite*>(tweens[i]));
		}
	}
}

//void KeyFrame::GetTweenSprite(ee::Sprite* start, ee::Sprite* end,
//							  ee::Sprite* tween, float process) const
//{
//	eanim::TweenUtility::GetTweenSprite(start, end, tween, process);
//
//	emesh::Sprite* s = dynamic_cast<emesh::Sprite*>(start),
//		*mid = dynamic_cast<emesh::Sprite*>(tween),
//		*e = static_cast<emesh::Sprite*>(end);
//	if (s && mid && e) {
//		mid->SetTween(s, e, process);
//	}
//}
//
//bool KeyFrame::IsTweenMatched(const ee::Sprite* s0, const ee::Sprite* s1) const
//{
//	if (eanim::TweenUtility::IsTweenMatched(s0, s1) &&
//		!m_skeleton.IsContainSprite(const_cast<ee::Sprite*>(s0))) {
//		return true;
//	} else {
//		return false;
//	}
//}

} // eanim<commit_msg>[FIXED] exception for debug<commit_after>#include "KeyFrame.h"
#include "LayersMgr.h"
#include "Layer.h"
#include "SpriteUserData.h"

#include <ee/ObjectVector.h>
#include <ee/Exception.h>

#include <easymesh.h>
#include <easyanim.h>
#include <easyparticle3d.h>

#include <sprite2/AnimLerp.h>

#include <algorithm>

namespace eanim
{

KeyFrame::KeyFrame(int time)
	: m_layer(NULL)
{
	m_time = time;
	m_classic_tween = false;
	m_id = 0;
}

KeyFrame::~KeyFrame()
{
	Clear();
}

void KeyFrame::SetLayer(Layer* layer)
{
	cu::RefCountObjAssign(m_layer, layer);
}

void KeyFrame::CopyFromOther(const KeyFrame* src)
{
	if (this == src) {
		return;
	}

	// sprs
	for (size_t i = 0, n = src->m_sprs.size(); i < n; ++i)
	{
		ee::Sprite* s = dynamic_cast<ee::Sprite*>(((cu::Cloneable*)src->m_sprs[i])->Clone());
		SpriteUserData::SetSprData(s, src->m_layer, this);
		m_sprs.push_back(s);

		if (src->m_layer) {
			s->SetObserver(&src->m_layer->GetSpriteObserver());
			src->m_layer->GetSpriteObserver().Insert(s, m_time);
		}
	}

	// skeleton
	m_skeleton.CopyFrom(m_sprs, src->m_skeleton);
	// todo spr's ud
}

void KeyFrame::Insert(ee::Sprite* spr, int idx)
{
	if (!spr) {
		throw ee::Exception("KeyFrame::Insert fail: spr null.");
	}
	spr->AddReference();

	if (!m_layer) {
		throw ee::Exception("KeyFrame::Insert: call zz see see.");
	}

	SpriteUserData::SetSprData(spr, m_layer, this);
	ee::ObjectVector<ee::Sprite>::Insert(m_sprs, spr, idx);
	if (m_layer) {
		spr->SetObserver(&m_layer->GetSpriteObserver());
		m_layer->GetSpriteObserver().Insert(spr, m_time);
	}
}

bool KeyFrame::Remove(ee::Sprite* spr)
{
	m_skeleton.RemoveSprite(spr);
	if (m_layer) {
		m_layer->GetSpriteObserver().Remove(spr);
	}

	return ee::ObjectVector<ee::Sprite>::Remove(m_sprs, spr);
}

bool KeyFrame::Reorder(const ee::Sprite* spr, bool up)
{
	return ee::ObjectVector<ee::Sprite>::ResetOrder(m_sprs, spr, up);
}

bool KeyFrame::ReorderMost(const ee::Sprite* spr, bool up)
{
	return ee::ObjectVector<ee::Sprite>::ResetOrderMost(m_sprs, spr, up);
}

bool KeyFrame::Sort(std::vector<ee::Sprite*>& sprs)
{
	return ee::ObjectVector<ee::Sprite>::Sort(m_sprs, sprs);
}

void KeyFrame::Clear()
{
	if (m_layer) {
		for (size_t i = 0, n = m_sprs.size(); i < n; ++i)
			m_layer->GetSpriteObserver().Remove(m_sprs[i]);
	}

	ee::ObjectVector<ee::Sprite>::Clear(m_sprs);
}

void KeyFrame::OnActive()
{
	for (int i = 0, n = m_sprs.size(); i < n; ++i) {
		if (eparticle3d::Sprite* p3d = dynamic_cast<eparticle3d::Sprite*>(m_sprs[i])) {
			if (p3d->IsAlone()) {
				p3d->OnActive();
			}
		}
	}
}

void KeyFrame::GetTweenSprite(const KeyFrame* start, const KeyFrame* end,
							  std::vector<ee::Sprite*>& tween, float process)
{
	// 	// old
	// 	for (int i = 0, n = start->Size(); i < n; ++i)
	// 	{
	// 		ee::Sprite* s = start->m_sprs[i];
	// 		for (int j = 0, m = end->Size(); j < m; ++j) {
	// 			ee::Sprite* e = end->m_sprs[j];
	// 			if (IsTweenMatched(s, e))
	// 			{
	// 				ee::Sprite* mid = s->clone();
	// 				GetTweenSprite(s, e, mid, process);
	// 				tween.push_back(mid);
	// 			}
	// 		}
	// 	}

	SkeletonData &s_skeleton = const_cast<KeyFrame*>(start)->GetSkeletonData(),
		         &e_skeleton = const_cast<KeyFrame*>(end)->GetSkeletonData();
	if (!s_skeleton.Empty() && !e_skeleton.Empty()) {
		SkeletonData::GetTweenSprites(s_skeleton, e_skeleton, tween, process);
	} else {
		std::vector<s2::Sprite*> begins, ends, tweens;
		begins.reserve(start->m_sprs.size());
		copy(start->m_sprs.begin(), start->m_sprs.end(), back_inserter(begins));
		ends.reserve(start->m_sprs.size());
		copy(end->m_sprs.begin(), end->m_sprs.end(), back_inserter(ends));

		s2::AnimLerp::Lerp(begins, ends, tweens, process);

		tween.reserve(tweens.size());
		for (int i = 0, n = tweens.size(); i < n; ++i) {
			tween.push_back(dynamic_cast<ee::Sprite*>(tweens[i]));
		}
	}
}

//void KeyFrame::GetTweenSprite(ee::Sprite* start, ee::Sprite* end,
//							  ee::Sprite* tween, float process) const
//{
//	eanim::TweenUtility::GetTweenSprite(start, end, tween, process);
//
//	emesh::Sprite* s = dynamic_cast<emesh::Sprite*>(start),
//		*mid = dynamic_cast<emesh::Sprite*>(tween),
//		*e = static_cast<emesh::Sprite*>(end);
//	if (s && mid && e) {
//		mid->SetTween(s, e, process);
//	}
//}
//
//bool KeyFrame::IsTweenMatched(const ee::Sprite* s0, const ee::Sprite* s1) const
//{
//	if (eanim::TweenUtility::IsTweenMatched(s0, s1) &&
//		!m_skeleton.IsContainSprite(const_cast<ee::Sprite*>(s0))) {
//		return true;
//	} else {
//		return false;
//	}
//}

} // eanim<|endoftext|>


<commit_before>/*
 * AttentionalFocusCB.cc
 *
 * Copyright (C) 2014 Misgana Bayetta
 *
 * Author: Misgana Bayetta <misgana.bayetta@gmail.com>  July 2014
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * 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 Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "AttentionalFocusCB.h"

using namespace opencog;

bool AttentionalFocusCB::node_match(Handle& node1, Handle& node2) {
	if (node1 == node2
			and node2->getAttentionValue()->getSTI()
					> _atom_space->getAttentionalFocusBoundary()) {
		return false;
	} else {
		return true;
	}
}

bool AttentionalFocusCB::link_match(LinkPtr& lpat, LinkPtr& lsoln) {
	if (DefaultPatternMatchCB::link_match(lpat, lsoln)) {
		return true;
	}
	if (lsoln->getAttentionValue()->getSTI()
			> _atom_space->getAttentionalFocusBoundary()) {
		return false;
	} else {
		return true;
	}
}

IncomingSet AttentionalFocusCB::get_incoming_set(Handle h) {
	const IncomingSet &incoming_set = h->getIncomingSet();
	IncomingSet filtered_set;
	for (IncomingSet::const_iterator i = incoming_set.begin();
			i != incoming_set.end(); ++i) {
		Handle candidate_handle(*i);
		if (candidate_handle->getAttentionValue()->getSTI()
				> _atom_space->getAttentionalFocusBoundary()) {
			filtered_set.push_back(LinkCast(candidate_handle));
		}

	}
	// if none is in AF
	if (filtered_set.empty()) {
		//xxx what shall we do here?, return the default or return empty ?

		filtered_set = incoming_set;
	}
	std::sort(filtered_set.begin(), filtered_set.end(), compare_sti); //sort by STI for better performance
	return filtered_set;
}

<commit_msg>changed node_match implementation<commit_after>/*
 * AttentionalFocusCB.cc
 *
 * Copyright (C) 2014 Misgana Bayetta
 *
 * Author: Misgana Bayetta <misgana.bayetta@gmail.com>  July 2014
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * 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 Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "AttentionalFocusCB.h"

using namespace opencog;

bool AttentionalFocusCB::node_match(Handle& node1, Handle& node2) {
	if (node1 == node2
			and node2->getAttentionValue()->getSTI()
					> _atom_space->getAttentionalFocusBoundary()) {
		return false;
	} else {

		return true;
	}
}

bool AttentionalFocusCB::link_match(LinkPtr& lpat, LinkPtr& lsoln) {
	if (DefaultPatternMatchCB::link_match(lpat, lsoln)) {
		return true;
	}
	if (lsoln->getAttentionValue()->getSTI()
			> _atom_space->getAttentionalFocusBoundary()) {
		return false;
	} else {
		return true;
	}
}

IncomingSet AttentionalFocusCB::get_incoming_set(Handle h) {
	const IncomingSet &incoming_set = h->getIncomingSet();
	IncomingSet filtered_set;
	for (IncomingSet::const_iterator i = incoming_set.begin();
			i != incoming_set.end(); ++i) {
		Handle candidate_handle(*i);
		if (candidate_handle->getAttentionValue()->getSTI()
				> _atom_space->getAttentionalFocusBoundary()) {
			filtered_set.push_back(LinkCast(candidate_handle));
		}

	}
	// if none is in AF
	if (filtered_set.empty()) {
		//xxx what shall we do here?, return the default or return empty ?

		filtered_set = incoming_set;
	}
	std::sort(filtered_set.begin(), filtered_set.end(), compare_sti); //sort by STI for better performance
	return filtered_set;
}

<|endoftext|>


<commit_before>/*************************************************************************/
/*  ip_unix.cpp                                                          */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur.                 */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#include "ip_unix.h"

#if defined(UNIX_ENABLED) || defined(WINDOWS_ENABLED)

#include <string.h>

#ifdef WINDOWS_ENABLED
#include <stdio.h>
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#ifndef UWP_ENABLED
#if defined(__MINGW32__) && (!defined(__MINGW64_VERSION_MAJOR) || __MINGW64_VERSION_MAJOR < 4)
// MinGW-w64 on Ubuntu 12.04 (our Travis build env) has bugs in this code where
// some includes are missing in dependencies of iphlpapi.h for WINVER >= 0x0600 (Vista).
// We don't use this Vista code for now, so working it around by disabling it.
// MinGW-w64 >= 4.0 seems to be better judging by its headers.
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0501 // Windows XP, disable Vista API
#include <iphlpapi.h>
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0600 // Reenable Vista API
#else
#include <iphlpapi.h>
#endif // MINGW hack
#endif
#else
#include <netdb.h>
#ifdef ANDROID_ENABLED
#include "platform/android/ifaddrs_android.h"
#else
#ifdef __FreeBSD__
#include <sys/types.h>
#endif
#include <ifaddrs.h>
#endif
#include <arpa/inet.h>
#include <sys/socket.h>
#ifdef __FreeBSD__
#include <netinet/in.h>
#endif
#endif

static IP_Address _sockaddr2ip(struct sockaddr *p_addr) {

	IP_Address ip;
	if (p_addr->sa_family == AF_INET) {
		struct sockaddr_in *addr = (struct sockaddr_in *)p_addr;
		ip.set_ipv4((uint8_t *)&(addr->sin_addr));
	} else {
		struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)p_addr;
		ip.set_ipv6(addr6->sin6_addr.s6_addr);
	};

	return ip;
};

IP_Address IP_Unix::_resolve_hostname(const String &p_hostname, Type p_type) {

	struct addrinfo hints;
	struct addrinfo *result;

	memset(&hints, 0, sizeof(struct addrinfo));
	if (p_type == TYPE_IPV4) {
		hints.ai_family = AF_INET;
	} else if (p_type == TYPE_IPV6) {
		hints.ai_family = AF_INET6;
		hints.ai_flags = 0;
	} else {
		hints.ai_family = AF_UNSPEC;
		hints.ai_flags = AI_ADDRCONFIG;
	};

	int s = getaddrinfo(p_hostname.utf8().get_data(), NULL, &hints, &result);
	if (s != 0) {
		ERR_PRINT("getaddrinfo failed!");
		return IP_Address();
	};

	if (result == NULL || result->ai_addr == NULL) {
		ERR_PRINT("Invalid response from getaddrinfo");
		return IP_Address();
	};

	IP_Address ip = _sockaddr2ip(result->ai_addr);

	freeaddrinfo(result);

	return ip;
}

#if defined(WINDOWS_ENABLED)

#if defined(UWP_ENABLED)

void IP_Unix::get_local_addresses(List<IP_Address> *r_addresses) const {

	using namespace Windows::Networking;
	using namespace Windows::Networking::Connectivity;

	auto hostnames = NetworkInformation::GetHostNames();

	for (int i = 0; i < hostnames->Size; i++) {

		if (hostnames->GetAt(i)->Type == HostNameType::Ipv4 || hostnames->GetAt(i)->Type == HostNameType::Ipv6 && hostnames->GetAt(i)->IPInformation != nullptr) {

			r_addresses->push_back(IP_Address(String(hostnames->GetAt(i)->CanonicalName->Data())));
		}
	}
};
#else

void IP_Unix::get_local_addresses(List<IP_Address> *r_addresses) const {

	ULONG buf_size = 1024;
	IP_ADAPTER_ADDRESSES *addrs;

	while (true) {

		addrs = (IP_ADAPTER_ADDRESSES *)memalloc(buf_size);
		int err = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST |
														  GAA_FLAG_SKIP_MULTICAST |
														  GAA_FLAG_SKIP_DNS_SERVER |
														  GAA_FLAG_SKIP_FRIENDLY_NAME,
				NULL, addrs, &buf_size);
		if (err == NO_ERROR) {
			break;
		};
		memfree(addrs);
		if (err == ERROR_BUFFER_OVERFLOW) {
			continue; // will go back and alloc the right size
		};

		ERR_EXPLAIN("Call to GetAdaptersAddresses failed with error " + itos(err));
		ERR_FAIL();
		return;
	};

	IP_ADAPTER_ADDRESSES *adapter = addrs;

	while (adapter != NULL) {

		IP_ADAPTER_UNICAST_ADDRESS *address = adapter->FirstUnicastAddress;
		while (address != NULL) {

			IP_Address ip;

			if (address->Address.lpSockaddr->sa_family == AF_INET) {

				SOCKADDR_IN *ipv4 = reinterpret_cast<SOCKADDR_IN *>(address->Address.lpSockaddr);

				ip.set_ipv4((uint8_t *)&(ipv4->sin_addr));
			} else { // ipv6

				SOCKADDR_IN6 *ipv6 = reinterpret_cast<SOCKADDR_IN6 *>(address->Address.lpSockaddr);

				ip.set_ipv6(ipv6->sin6_addr.s6_addr);
			};

			r_addresses->push_back(ip);

			address = address->Next;
		};
		adapter = adapter->Next;
	};

	memfree(addrs);
};

#endif

#else

void IP_Unix::get_local_addresses(List<IP_Address> *r_addresses) const {

	struct ifaddrs *ifAddrStruct = NULL;
	struct ifaddrs *ifa = NULL;

	getifaddrs(&ifAddrStruct);

	for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
		if (!ifa->ifa_addr)
			continue;

		IP_Address ip = _sockaddr2ip(ifa->ifa_addr);
		r_addresses->push_back(ip);
	}

	if (ifAddrStruct != NULL) freeifaddrs(ifAddrStruct);
}
#endif

void IP_Unix::make_default() {

	_create = _create_unix;
}

IP *IP_Unix::_create_unix() {

	return memnew(IP_Unix);
}

IP_Unix::IP_Unix() {
}

#endif
<commit_msg>Fix build issue with MSVC<commit_after>/*************************************************************************/
/*  ip_unix.cpp                                                          */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur.                 */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#include "ip_unix.h"

#if defined(UNIX_ENABLED) || defined(WINDOWS_ENABLED)

#include <string.h>

#ifdef WINDOWS_ENABLED
#include <stdio.h>
#include <winsock2.h>
// Needs to be included after winsocks2.h
#include <windows.h>
#include <ws2tcpip.h>
#ifndef UWP_ENABLED
#if defined(__MINGW32__) && (!defined(__MINGW64_VERSION_MAJOR) || __MINGW64_VERSION_MAJOR < 4)
// MinGW-w64 on Ubuntu 12.04 (our Travis build env) has bugs in this code where
// some includes are missing in dependencies of iphlpapi.h for WINVER >= 0x0600 (Vista).
// We don't use this Vista code for now, so working it around by disabling it.
// MinGW-w64 >= 4.0 seems to be better judging by its headers.
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0501 // Windows XP, disable Vista API
#include <iphlpapi.h>
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0600 // Reenable Vista API
#else
#include <iphlpapi.h>
#endif // MINGW hack
#endif
#else
#include <netdb.h>
#ifdef ANDROID_ENABLED
#include "platform/android/ifaddrs_android.h"
#else
#ifdef __FreeBSD__
#include <sys/types.h>
#endif
#include <ifaddrs.h>
#endif
#include <arpa/inet.h>
#include <sys/socket.h>
#ifdef __FreeBSD__
#include <netinet/in.h>
#endif
#endif

static IP_Address _sockaddr2ip(struct sockaddr *p_addr) {

	IP_Address ip;
	if (p_addr->sa_family == AF_INET) {
		struct sockaddr_in *addr = (struct sockaddr_in *)p_addr;
		ip.set_ipv4((uint8_t *)&(addr->sin_addr));
	} else {
		struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)p_addr;
		ip.set_ipv6(addr6->sin6_addr.s6_addr);
	};

	return ip;
};

IP_Address IP_Unix::_resolve_hostname(const String &p_hostname, Type p_type) {

	struct addrinfo hints;
	struct addrinfo *result;

	memset(&hints, 0, sizeof(struct addrinfo));
	if (p_type == TYPE_IPV4) {
		hints.ai_family = AF_INET;
	} else if (p_type == TYPE_IPV6) {
		hints.ai_family = AF_INET6;
		hints.ai_flags = 0;
	} else {
		hints.ai_family = AF_UNSPEC;
		hints.ai_flags = AI_ADDRCONFIG;
	};

	int s = getaddrinfo(p_hostname.utf8().get_data(), NULL, &hints, &result);
	if (s != 0) {
		ERR_PRINT("getaddrinfo failed!");
		return IP_Address();
	};

	if (result == NULL || result->ai_addr == NULL) {
		ERR_PRINT("Invalid response from getaddrinfo");
		return IP_Address();
	};

	IP_Address ip = _sockaddr2ip(result->ai_addr);

	freeaddrinfo(result);

	return ip;
}

#if defined(WINDOWS_ENABLED)

#if defined(UWP_ENABLED)

void IP_Unix::get_local_addresses(List<IP_Address> *r_addresses) const {

	using namespace Windows::Networking;
	using namespace Windows::Networking::Connectivity;

	auto hostnames = NetworkInformation::GetHostNames();

	for (int i = 0; i < hostnames->Size; i++) {

		if (hostnames->GetAt(i)->Type == HostNameType::Ipv4 || hostnames->GetAt(i)->Type == HostNameType::Ipv6 && hostnames->GetAt(i)->IPInformation != nullptr) {

			r_addresses->push_back(IP_Address(String(hostnames->GetAt(i)->CanonicalName->Data())));
		}
	}
};
#else

void IP_Unix::get_local_addresses(List<IP_Address> *r_addresses) const {

	ULONG buf_size = 1024;
	IP_ADAPTER_ADDRESSES *addrs;

	while (true) {

		addrs = (IP_ADAPTER_ADDRESSES *)memalloc(buf_size);
		int err = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST |
														  GAA_FLAG_SKIP_MULTICAST |
														  GAA_FLAG_SKIP_DNS_SERVER |
														  GAA_FLAG_SKIP_FRIENDLY_NAME,
				NULL, addrs, &buf_size);
		if (err == NO_ERROR) {
			break;
		};
		memfree(addrs);
		if (err == ERROR_BUFFER_OVERFLOW) {
			continue; // will go back and alloc the right size
		};

		ERR_EXPLAIN("Call to GetAdaptersAddresses failed with error " + itos(err));
		ERR_FAIL();
		return;
	};

	IP_ADAPTER_ADDRESSES *adapter = addrs;

	while (adapter != NULL) {

		IP_ADAPTER_UNICAST_ADDRESS *address = adapter->FirstUnicastAddress;
		while (address != NULL) {

			IP_Address ip;

			if (address->Address.lpSockaddr->sa_family == AF_INET) {

				SOCKADDR_IN *ipv4 = reinterpret_cast<SOCKADDR_IN *>(address->Address.lpSockaddr);

				ip.set_ipv4((uint8_t *)&(ipv4->sin_addr));
			} else { // ipv6

				SOCKADDR_IN6 *ipv6 = reinterpret_cast<SOCKADDR_IN6 *>(address->Address.lpSockaddr);

				ip.set_ipv6(ipv6->sin6_addr.s6_addr);
			};

			r_addresses->push_back(ip);

			address = address->Next;
		};
		adapter = adapter->Next;
	};

	memfree(addrs);
};

#endif

#else

void IP_Unix::get_local_addresses(List<IP_Address> *r_addresses) const {

	struct ifaddrs *ifAddrStruct = NULL;
	struct ifaddrs *ifa = NULL;

	getifaddrs(&ifAddrStruct);

	for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
		if (!ifa->ifa_addr)
			continue;

		IP_Address ip = _sockaddr2ip(ifa->ifa_addr);
		r_addresses->push_back(ip);
	}

	if (ifAddrStruct != NULL) freeifaddrs(ifAddrStruct);
}
#endif

void IP_Unix::make_default() {

	_create = _create_unix;
}

IP *IP_Unix::_create_unix() {

	return memnew(IP_Unix);
}

IP_Unix::IP_Unix() {
}

#endif
<|endoftext|>


<commit_before>/*
  Copyright (c) 2017 Fatih Kaya
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"),
  to deal in the Software without restriction, including without limitation
  the rights to use, copy, modify, merge, publish, distribute, sublicense,
  and/or sell copies of the Software, and to permit persons to whom
  the Software is furnished to do so, subject to the following conditions:
  The above copyright notice and this permission notice shall be included
  in all copies or substantial portions of the Software.
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  IN THE SOFTWARE.
*/

#include "table.hh"

using namespace jill::table;
using namespace std;

int main(int argc, char *argv[]) {
  jill::table::Table table;
  jill::table::Field<jill::table::TIMESTAMP, int64_t> *timestamp = new jill::table::Field<jill::table::TIMESTAMP, int64_t>("timestamp");
  Field<DIMENSION, string> *country = new Field<DIMENSION, string>("country");
  Field<BOOL, bool> *isClick = new Field<BOOL, bool>("isClick");
  Field<METRIC_FLOAT, float> *price = new Field<METRIC_FLOAT, float>("price");

  table.addField<TIMESTAMP, int64_t>(timestamp);
  table.addField<DIMENSION, string>(country);
  table.addField<BOOL, bool>(isClick);
  table.addField<METRIC_FLOAT, float>(price);

  // insert values
  int64_t ts = 1;
  string countryTR = "turkey";
  bool isClickVal = false;
  float priceVal = 1.99;

  timestamp->insert(ts);
  country->insert(countryTR);
  isClick->insert(isClickVal);
  price->insert(priceVal);

  //////////////////////////////////
  // query the table
  //////////////////////////////////
  Query query;
  // add filters
  Filter filter1("isClick", "true", EQUAL);
  Filter filter2("country", "turkey", EQUAL);
  query.addFilter(&filter1);
  query.addFilter(&filter2);

  return 0;
}
<commit_msg>call executeQuery<commit_after>/*
  Copyright (c) 2017 Fatih Kaya
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"),
  to deal in the Software without restriction, including without limitation
  the rights to use, copy, modify, merge, publish, distribute, sublicense,
  and/or sell copies of the Software, and to permit persons to whom
  the Software is furnished to do so, subject to the following conditions:
  The above copyright notice and this permission notice shall be included
  in all copies or substantial portions of the Software.
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  IN THE SOFTWARE.
*/

#include "table.hh"

using namespace jill::table;
using namespace std;

int main(int argc, char *argv[]) {
  jill::table::Table table;
  jill::table::Field<jill::table::TIMESTAMP, int64_t> *timestamp = new jill::table::Field<jill::table::TIMESTAMP, int64_t>("timestamp");
  Field<DIMENSION, string> *country = new Field<DIMENSION, string>("country");
  Field<BOOL, bool> *isClick = new Field<BOOL, bool>("isClick");
  Field<METRIC_FLOAT, float> *price = new Field<METRIC_FLOAT, float>("price");

  table.addField<TIMESTAMP, int64_t>(timestamp);
  table.addField<DIMENSION, string>(country);
  table.addField<BOOL, bool>(isClick);
  table.addField<METRIC_FLOAT, float>(price);

  // insert values
  int64_t ts = 1;
  string countryTR = "turkey";
  bool isClickVal = false;
  float priceVal = 1.99;

  timestamp->insert(ts);
  country->insert(countryTR);
  isClick->insert(isClickVal);
  price->insert(priceVal);

  //////////////////////////////////
  // query the table
  //////////////////////////////////
  Query query;
  // add filters
  Filter filter1("isClick", "true", EQUAL);
  Filter filter2("country", "turkey", EQUAL);
  query.addFilter(&filter1);
  query.addFilter(&filter2);

  table.executeQuery(query);

  return 0;
}
<|endoftext|>