<commit_before>/*
 * Copyright 2014-2015 Adrián Arroyo Calle <adrian.arroyocalle@gmail.com>
 * All rights reserved. Distributed under the terms of the MIT license.
 */

#include "App.hpp"
#include "Window.hpp"

SuperFreeCell::SuperFreeCell()
		:
		BApplication("application/x-vnd.adrianarroyocalle.SuperFreeCell")
{
	Window* win=new Window();
	win->Lock();
	win->Show();
	win->Unlock();
}

SuperFreeCell::~SuperFreeCell()
{

}

void
SuperFreeCell::AboutRequested()
{
	BString aboutText="";
	aboutText << "SuperFreeCell 0.1 \n";
	aboutText << "A freecell clone for Haiku \n";
	aboutText << "\n";
	aboutText << "2014 Adrián Arroyo Calle <adrian.arroyocalle@gmail.com>\n";
	aboutText << "Licensed under the MIT license\n";

	BAlert* about=new BAlert("About",aboutText,"OK");
	about->Go();
}

int
main(int argc, char** argv)
{
	SuperFreeCell app;
	app.Run();
	return 0;
}

<commit_msg>Change year in About Dialog<commit_after>/*
 * Copyright 2014-2015 Adrián Arroyo Calle <adrian.arroyocalle@gmail.com>
 * All rights reserved. Distributed under the terms of the MIT license.
 */

#include "App.hpp"
#include "Window.hpp"

SuperFreeCell::SuperFreeCell()
		:
		BApplication("application/x-vnd.adrianarroyocalle.SuperFreeCell")
{
	Window* win=new Window();
	win->Lock();
	win->Show();
	win->Unlock();
}

SuperFreeCell::~SuperFreeCell()
{

}

void
SuperFreeCell::AboutRequested()
{
	BString aboutText="";
	aboutText << "SuperFreeCell 0.1 \n";
	aboutText << "A freecell clone for Haiku \n";
	aboutText << "\n";
	aboutText << "2014-2015 Adrián Arroyo Calle <adrian.arroyocalle@gmail.com>\n";
	aboutText << "Licensed under the MIT license\n";

	BAlert* about=new BAlert("About",aboutText,"OK");
	about->Go();
}

int
main(int argc, char** argv)
{
	SuperFreeCell app;
	app.Run();
	return 0;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
#include "boost/program_options.hpp"
#include "boost/shared_ptr.hpp"

#include "Model.h"
#include "Timer.h"
#include "CycException.h"
#include "Env.h"
#include "Logger.h"
#include "XMLFileLoader.h"
#include "EventManager.h"
#include "SqliteBack.h"

using namespace std;
namespace po = boost::program_options;

//-----------------------------------------------------------------------
// Main entry point for the test application...
//-----------------------------------------------------------------------
int main(int argc, char* argv[]) {
  // verbosity help msg
  std::string vmessage = "output log verbosity. Can be text:\n\n";
  vmessage += "   LEV_ERROR (least verbose, default), LEV_WARN, \n   LEV_INFO1 (through 5), and LEV_DEBUG1 (through 5).\n\n";
  vmessage += "Or an integer:\n\n   0 (LEV_ERROR equiv) through 11 (LEV_DEBUG5 equiv)\n";

  // parse command line options
  po::options_description desc("Allowed options");
  desc.add_options()
    ("help,h", "produce help message")
    ("no-model", "only print log entries from cyclus core code")
    ("no-mem", "exclude memory log statement from logger output")
    ("verb,v", po::value<string>(), vmessage.c_str())
    ("output-path,o", po::value<string>(), "output path")
    ("input-file", po::value<string>(), "input file")
    ;

  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);

  po::positional_options_description p;
  p.add("input-file", 1);

  //po::variables_map vm;
  po::store(po::command_line_parser(argc, argv).
            options(desc).positional(p).run(), vm);
  po::notify(vm);

  // announce yourself
  cout << endl;
  cout << "|--------------------------------------------|" << endl;
  cout << "|                  Cyclus                    |" << endl;
  cout << "|       a nuclear fuel cycle simulator       |" << endl;
  cout << "|  from the University of Wisconsin-Madison  |" << endl;
  cout << "|--------------------------------------------|" << endl;
  cout << endl;

  bool success = true;

  // respond to command line args
  if (vm.count("help")) {
    string err_msg = "Cyclus usage requires an input file.\n";
    err_msg += "Usage:   cyclus [path/to/input/filename]\n";
    cout << err_msg << endl;
    cout << desc << "\n";
    return 0;
  }

  if (vm.count("no-model")) {
    Logger::NoModel() = true;
  }

  if (vm.count("no-mem")) {
    Logger::NoMem() = true;
  }

  if (! vm.count("input-file")) {
    string err_msg = "Cyclus usage requires an input file.\n";
    err_msg += "Usage:   cyclus [path/to/input/filename]\n";
    cout << err_msg << endl;
    cout << desc << "\n";
    return 0;
  }

  if (vm.count("verb")) {
    std::string v_level = vm["verb"].as<string>();
    if (v_level.length() < 3) {
      Logger::ReportLevel() = (LogLevel)strtol(v_level.c_str(), NULL, 10);
    } else {
      Logger::ReportLevel() = Logger::ToLogLevel(v_level);
    }
  }

  // tell ENV the path between the cwd and the cyclus executable
  string path = Env::pathBase(argv[0]);
  Env::setCyclusRelPath(path);

  // read input file and setup simulation
  try {
    string inputFile = vm["input-file"].as<string>();
    set<string> module_types = Model::dynamic_module_types();
    XMLFileLoader loader(inputFile);
    loader.init();
    loader.load_control_parameters();
    loader.load_recipes();
    loader.load_dynamic_modules(module_types);
  } catch (CycException e) {
    success = false;
    CLOG(LEV_ERROR) << e.what();
  }

  // Create the output file
  string output_path = "cyclus.sqlite";
  try {
    if (vm.count("output-path")){
      output_path = vm["output-path"].as<string>();
    }
  } catch (CycException ge) {
    success = false;
    CLOG(LEV_ERROR) << ge.what();
  }
  SqliteBack* sqlBack = new SqliteBack(EM->sim_id(), output_path);
  EM->registerBackend(sqlBack);

  // sim construction - should be handled by some entity
  Model::constructSimulation();

  // print the model list
  Model::printModelList();

  // Run the simulation
  try {
    TI->runSim();
  } catch (CycException err) {
    success = false;
    CLOG(LEV_ERROR) << err.what();
  }

  EM->close();

  // Close Dynamically loaded modules
  try {
    Model::unloadModules();
  } catch (CycException err) {
    success = false;
    CLOG(LEV_ERROR) << err.what();
  }

  if (success) {
    cout << endl;
    cout << "|--------------------------------------------|" << endl;
    cout << "|                  Cyclus                    |" << endl;
    cout << "|              run successful                |" << endl;
    cout << "|--------------------------------------------|" << endl;
    cout << "Output location: " << output_path << endl;
    cout << "Simulation ID: " << EM->sim_id() << endl;
    cout << endl;
  } else {
    cout << endl;
    cout << "|--------------------------------------------|" << endl;
    cout << "|                  Cyclus                    |" << endl;
    cout << "|           run *not* successful             |" << endl;
    cout << "|--------------------------------------------|" << endl;
    cout << endl;
  }

  return 0;
}
<commit_msg>moved sqliteback allocation to the stack. closes #513.<commit_after>#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
#include "boost/program_options.hpp"
#include "boost/shared_ptr.hpp"

#include "Model.h"
#include "Timer.h"
#include "CycException.h"
#include "Env.h"
#include "Logger.h"
#include "XMLFileLoader.h"
#include "EventManager.h"
#include "SqliteBack.h"

using namespace std;
namespace po = boost::program_options;

//-----------------------------------------------------------------------
// Main entry point for the test application...
//-----------------------------------------------------------------------
int main(int argc, char* argv[]) {
  // verbosity help msg
  std::string vmessage = "output log verbosity. Can be text:\n\n";
  vmessage += "   LEV_ERROR (least verbose, default), LEV_WARN, \n   LEV_INFO1 (through 5), and LEV_DEBUG1 (through 5).\n\n";
  vmessage += "Or an integer:\n\n   0 (LEV_ERROR equiv) through 11 (LEV_DEBUG5 equiv)\n";

  // parse command line options
  po::options_description desc("Allowed options");
  desc.add_options()
    ("help,h", "produce help message")
    ("no-model", "only print log entries from cyclus core code")
    ("no-mem", "exclude memory log statement from logger output")
    ("verb,v", po::value<string>(), vmessage.c_str())
    ("output-path,o", po::value<string>(), "output path")
    ("input-file", po::value<string>(), "input file")
    ;

  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);

  po::positional_options_description p;
  p.add("input-file", 1);

  //po::variables_map vm;
  po::store(po::command_line_parser(argc, argv).
            options(desc).positional(p).run(), vm);
  po::notify(vm);

  // announce yourself
  cout << endl;
  cout << "|--------------------------------------------|" << endl;
  cout << "|                  Cyclus                    |" << endl;
  cout << "|       a nuclear fuel cycle simulator       |" << endl;
  cout << "|  from the University of Wisconsin-Madison  |" << endl;
  cout << "|--------------------------------------------|" << endl;
  cout << endl;

  bool success = true;

  // respond to command line args
  if (vm.count("help")) {
    string err_msg = "Cyclus usage requires an input file.\n";
    err_msg += "Usage:   cyclus [path/to/input/filename]\n";
    cout << err_msg << endl;
    cout << desc << "\n";
    return 0;
  }

  if (vm.count("no-model")) {
    Logger::NoModel() = true;
  }

  if (vm.count("no-mem")) {
    Logger::NoMem() = true;
  }

  if (! vm.count("input-file")) {
    string err_msg = "Cyclus usage requires an input file.\n";
    err_msg += "Usage:   cyclus [path/to/input/filename]\n";
    cout << err_msg << endl;
    cout << desc << "\n";
    return 0;
  }

  if (vm.count("verb")) {
    std::string v_level = vm["verb"].as<string>();
    if (v_level.length() < 3) {
      Logger::ReportLevel() = (LogLevel)strtol(v_level.c_str(), NULL, 10);
    } else {
      Logger::ReportLevel() = Logger::ToLogLevel(v_level);
    }
  }

  // tell ENV the path between the cwd and the cyclus executable
  string path = Env::pathBase(argv[0]);
  Env::setCyclusRelPath(path);

  // read input file and setup simulation
  try {
    string inputFile = vm["input-file"].as<string>();
    set<string> module_types = Model::dynamic_module_types();
    XMLFileLoader loader(inputFile);
    loader.init();
    loader.load_control_parameters();
    loader.load_recipes();
    loader.load_dynamic_modules(module_types);
  } catch (CycException e) {
    success = false;
    CLOG(LEV_ERROR) << e.what();
  }

  // Create the output file
  string output_path = "cyclus.sqlite";
  try {
    if (vm.count("output-path")){
      output_path = vm["output-path"].as<string>();
    }
  } catch (CycException ge) {
    success = false;
    CLOG(LEV_ERROR) << ge.what();
  }
  SqliteBack sqlBack = SqliteBack(EM->sim_id(), output_path);
  EM->registerBackend(&sqlBack);

  // sim construction - should be handled by some entity
  Model::constructSimulation();

  // print the model list
  Model::printModelList();

  // Run the simulation
  try {
    TI->runSim();
  } catch (CycException err) {
    success = false;
    CLOG(LEV_ERROR) << err.what();
  }

  EM->close();

  // Close Dynamically loaded modules
  try {
    Model::unloadModules();
  } catch (CycException err) {
    success = false;
    CLOG(LEV_ERROR) << err.what();
  }

  if (success) {
    cout << endl;
    cout << "|--------------------------------------------|" << endl;
    cout << "|                  Cyclus                    |" << endl;
    cout << "|              run successful                |" << endl;
    cout << "|--------------------------------------------|" << endl;
    cout << "Output location: " << output_path << endl;
    cout << "Simulation ID: " << EM->sim_id() << endl;
    cout << endl;
  } else {
    cout << endl;
    cout << "|--------------------------------------------|" << endl;
    cout << "|                  Cyclus                    |" << endl;
    cout << "|           run *not* successful             |" << endl;
    cout << "|--------------------------------------------|" << endl;
    cout << endl;
  }

  return 0;
}
<|endoftext|>


<commit_before>#include <igloo/igloo_alt.h>
#include <Landmarks.hh>

namespace	Landmark_Result
{
  int		id = -1;
  int		life = LIFE;
  int		totalTimesObserved = 0;
  double	range = -1;
  double	bearing = -1;
  double	pos[2] = {0.0, 0.0};
};

namespace	Landmarks_Result
{
  int		DBSize = 0;
  int		EKFLandmarks = 0;
  double	defaultdegreePerScan = DEGREESPERSCAN;
  double	degreePerScan = 0.4;
  int		sizeIDtoID = MAXLANDMARKS;
  int		sizelandmarkDB = MAXLANDMARKS;
};

using namespace igloo;

When(creating_a_landmark)
{
  Then(it_should_have_default_value)
    {
      Assert::That(lm.id, Is().EqualTo(::Landmark_Result::id));
      Assert::That(lm.life, Is().EqualTo(::Landmark_Result::life));
      Assert::That(lm.totalTimeObserved, Is().EqualTo(::Landmark_Result::totalTimesObserved));
      Assert::That(lm.range, Is().EqualTo(::Landmark_Result::range));
      Assert::That(lm.bearing, Is().EqualTo(::Landmark_Result::bearing));
      Assert::That(lm.pos[0], Is().EqualTo(::Landmark_Result::pos[0]));
      Assert::That(lm.pos[1], Is().EqualTo(::Landmark_Result::pos[1]));
    }

  ::Landmarks::Landmark	lm;
};

When(creating_Landmarks)
{
  Then(it_should_have_default_landmarks_value)
  {
    Assert::That(lms.DBSize, Is().EqualTo(::Landmarks_Result::DBSize));
    Assert::That(lms.EKFLandmarks, Is().EqualTo(::Landmarks_Result::EKFLandmarks));
    Assert::That(lms.degreePerScan, Is().EqualTo(::Landmarks_Result::defaultdegreePerScan));
    Assert::That(lms.IDtoID.capacity(), Is().EqualTo(::Landmarks_Result::sizeIDtoID));
    Assert::That(lms.landmarkDB.capacity(), Is().EqualTo(::Landmarks_Result::sizelandmarkDB));
  }

  Landmarks lms;
};
<commit_msg>SLAM: Test: Landmarks(double)<commit_after>#include <igloo/igloo_alt.h>
#include <Landmarks.hh>

namespace	Landmark_Result
{
  int		id = -1;
  int		life = LIFE;
  int		totalTimesObserved = 0;
  double	range = -1;
  double	bearing = -1;
  double	pos[2] = {0.0, 0.0};
};

namespace	Landmarks_Result
{
  int		DBSize = 0;
  int		EKFLandmarks = 0;
  double	defaultdegreePerScan = DEGREESPERSCAN;
  double	degreePerScan = 0.42;
  int		sizeIDtoID = MAXLANDMARKS;
  int		sizelandmarkDB = MAXLANDMARKS;
};

using namespace igloo;

When(creating_a_landmark)
{
  Then(it_should_have_default_value)
    {
      Assert::That(lm.id, Is().EqualTo(::Landmark_Result::id));
      Assert::That(lm.life, Is().EqualTo(::Landmark_Result::life));
      Assert::That(lm.totalTimeObserved, Is().EqualTo(::Landmark_Result::totalTimesObserved));
      Assert::That(lm.range, Is().EqualTo(::Landmark_Result::range));
      Assert::That(lm.bearing, Is().EqualTo(::Landmark_Result::bearing));
      Assert::That(lm.pos[0], Is().EqualTo(::Landmark_Result::pos[0]));
      Assert::That(lm.pos[1], Is().EqualTo(::Landmark_Result::pos[1]));
    }

  ::Landmarks::Landmark	lm;
};

When(creating_Landmarks)
{
  Then(it_should_have_default_landmarks_value)
  {
    Assert::That(lms.DBSize, Is().EqualTo(::Landmarks_Result::DBSize));
    Assert::That(lms.EKFLandmarks, Is().EqualTo(::Landmarks_Result::EKFLandmarks));
    Assert::That(lms.degreePerScan, Is().EqualTo(::Landmarks_Result::defaultdegreePerScan));
    Assert::That(lms.IDtoID.capacity(), Is().EqualTo(::Landmarks_Result::sizeIDtoID));
    Assert::That(lms.landmarkDB.capacity(), Is().EqualTo(::Landmarks_Result::sizelandmarkDB));
  }

  Landmarks lms;
};

When(creating_Landmarks_with_a_specific_degree_value_different_from_default)
{
  void SetUp()
  {
    lms = new ::Landmarks(::Landmarks_Result::degreePerScan);
  }

  Then(it_should_not_have_default_degree_value)
  {
    Assert::That(lms->degreePerScan, Is().Not().EqualTo(::Landmarks_Result::defaultdegreePerScan));
  }

  Then(it_should_have_this_specific_degree_value)
  {
    Assert::That(lms->degreePerScan, Is().EqualTo(::Landmarks_Result::degreePerScan));
  }

  void	TearDown()
  {
    delete lms;
  }

  Landmarks *lms;
};

<|endoftext|>


<commit_before>#include "drawer.hh"

#include <cmath>
#include <cstring>
#include <deque>
#include <fstream>
#include <stdexcept>

#include "bezier.hh"

const std::vector<CanvasPoint> create_path_from_track(const std::shared_ptr<Projection> & projection,
                                                      const Track & track, const std::shared_ptr<const SolarObject> & object)
{
    std::vector<CanvasPoint> path;
    double step(track.mark_interval / track.interval_ticks);

    for (double t(0); t <= track.length.val(); t += step)
    {
        auto coord(object->get_equ_coords(track.start.val() + t));
        path.push_back(projection->project(coord));
    }

    return path;
}

const std::deque<BezierCurve> create_bezier_from_path(const std::shared_ptr<Projection> & projection, const std::vector<ln_equ_posn> & path)
{
    std::vector<CanvasPoint> ret;
    for (auto const & p : path)
    {
        ret.push_back(projection->project(p));
    }
    return create_bezier_from_path(ret);
}

const std::deque<BezierCurve> create_bezier_from_path(const std::vector<CanvasPoint> & path)
{
    {
        std::vector<std::vector<CanvasPoint>> input(1);
        for (auto const & p : path)
        {
            if (! p.nan())
                input.back().push_back(p);
            else if (! input.back().empty())
                input.push_back(std::vector<CanvasPoint>());
        }

        std::deque<BezierCurve> ret;
        for (auto const & b : input)
        {
            if (b.size() < 2)
                continue;

            ret.push_back(interpolate_bezier(b));
        }

        return ret;
    }
}
<commit_msg>too many blocks<commit_after>#include "drawer.hh"

#include <cmath>
#include <cstring>
#include <deque>
#include <fstream>
#include <stdexcept>

#include "bezier.hh"

const std::vector<CanvasPoint> create_path_from_track(const std::shared_ptr<Projection> & projection,
                                                      const Track & track, const std::shared_ptr<const SolarObject> & object)
{
    std::vector<CanvasPoint> path;
    double step(track.mark_interval / track.interval_ticks);

    for (double t(0); t <= track.length.val(); t += step)
    {
        auto coord(object->get_equ_coords(track.start.val() + t));
        path.push_back(projection->project(coord));
    }

    return path;
}

const std::deque<BezierCurve> create_bezier_from_path(const std::shared_ptr<Projection> & projection, const std::vector<ln_equ_posn> & path)
{
    std::vector<CanvasPoint> ret;
    for (auto const & p : path)
    {
        ret.push_back(projection->project(p));
    }
    return create_bezier_from_path(ret);
}

const std::deque<BezierCurve> create_bezier_from_path(const std::vector<CanvasPoint> & path)
{
    std::vector<std::vector<CanvasPoint>> input(1);
    for (auto const & p : path)
    {
        if (! p.nan())
            input.back().push_back(p);
        else if (! input.back().empty())
            input.push_back(std::vector<CanvasPoint>());
    }

    std::deque<BezierCurve> ret;
    for (auto const & b : input)
    {
        if (b.size() < 2)
            continue;

        ret.push_back(interpolate_bezier(b));
    }

    return ret;
}
<|endoftext|>


<commit_before>#include "master.hpp"

namespace factor
{

void factor_vm::init_card_decks()
{
	cards_offset = (cell)data->cards - addr_to_card(data->start);
	decks_offset = (cell)data->decks - addr_to_deck(data->start);
}

data_heap::data_heap(cell young_size_,
	cell aging_size_,
	cell tenured_size_)
{
	young_size_ = align(young_size_,deck_size);
	aging_size_ = align(aging_size_,deck_size);
	tenured_size_ = align(tenured_size_,deck_size);

	young_size = young_size_;
	aging_size = aging_size_;
	tenured_size = tenured_size_;

	cell total_size = young_size + 2 * aging_size + tenured_size + deck_size;
	seg = new segment(total_size,false);

	cell cards_size = addr_to_card(total_size);
	cards = new card[cards_size];
	cards_end = cards + cards_size;
	memset(cards,0,cards_size);

	cell decks_size = addr_to_deck(total_size);
	decks = new card_deck[decks_size];
	decks_end = decks + decks_size;
	memset(decks,0,decks_size);

	start = align(seg->start,deck_size);

	tenured = new tenured_space(tenured_size,start);

	aging = new aging_space(aging_size,tenured->end);
	aging_semispace = new aging_space(aging_size,aging->end);

	nursery = new nursery_space(young_size,aging_semispace->end);

	assert(seg->end - nursery->end <= deck_size);
}

data_heap::~data_heap()
{
	delete seg;
	delete nursery;
	delete aging;
	delete aging_semispace;
	delete tenured;
	delete[] cards;
	delete[] decks;
}

data_heap *data_heap::grow(cell requested_bytes)
{
	cell new_tenured_size = (tenured_size * 2) + requested_bytes;
	return new data_heap(young_size,
		aging_size,
		new_tenured_size);
}

template<typename Generation> void data_heap::clear_cards(Generation *gen)
{
	cell first_card = addr_to_card(gen->start - start);
	cell last_card = addr_to_card(gen->end - start);
	memset(&cards[first_card],0,last_card - first_card);
}

template<typename Generation> void data_heap::clear_decks(Generation *gen)
{
	cell first_deck = addr_to_deck(gen->start - start);
	cell last_deck = addr_to_deck(gen->end - start);
	memset(&decks[first_deck],0,last_deck - first_deck);
}

void data_heap::reset_generation(nursery_space *gen)
{
	gen->here = gen->start;
}

void data_heap::reset_generation(aging_space *gen)
{
	gen->here = gen->start;
	clear_cards(gen);
	clear_decks(gen);
	gen->starts.clear_object_start_offsets();
}

void data_heap::reset_generation(tenured_space *gen)
{
	clear_cards(gen);
	clear_decks(gen);
}

bool data_heap::low_memory_p()
{
	return (tenured->free_space() <= nursery->size + aging->size);
}

void data_heap::mark_all_cards()
{
	memset(cards,-1,cards_end - cards);
	memset(decks,-1,decks_end - decks);
}

void factor_vm::set_data_heap(data_heap *data_)
{
	data = data_;
	nursery = *data->nursery;
	init_card_decks();
}

void factor_vm::init_data_heap(cell young_size, cell aging_size, cell tenured_size)
{
	set_data_heap(new data_heap(young_size,aging_size,tenured_size));
}

/* Size of the object pointed to by an untagged pointer */
cell object::size() const
{
	if(free_p()) return ((free_heap_block *)this)->size();

	switch(h.hi_tag())
	{
	case ARRAY_TYPE:
		return align(array_size((array*)this),data_alignment);
	case BIGNUM_TYPE:
		return align(array_size((bignum*)this),data_alignment);
	case BYTE_ARRAY_TYPE:
		return align(array_size((byte_array*)this),data_alignment);
	case STRING_TYPE:
		return align(string_size(string_capacity((string*)this)),data_alignment);
	case TUPLE_TYPE:
		{
			tuple_layout *layout = (tuple_layout *)UNTAG(((tuple *)this)->layout);
			return align(tuple_size(layout),data_alignment);
		}
	case QUOTATION_TYPE:
		return align(sizeof(quotation),data_alignment);
	case WORD_TYPE:
		return align(sizeof(word),data_alignment);
	case FLOAT_TYPE:
		return align(sizeof(boxed_float),data_alignment);
	case DLL_TYPE:
		return align(sizeof(dll),data_alignment);
	case ALIEN_TYPE:
		return align(sizeof(alien),data_alignment);
	case WRAPPER_TYPE:
		return align(sizeof(wrapper),data_alignment);
	case CALLSTACK_TYPE:
		return align(callstack_size(untag_fixnum(((callstack *)this)->length)),data_alignment);
	default:
		critical_error("Invalid header",(cell)this);
		return 0; /* can't happen */
	}
}

/* The number of cells from the start of the object which should be scanned by
the GC. Some types have a binary payload at the end (string, word, DLL) which
we ignore. */
cell object::binary_payload_start() const
{
	switch(h.hi_tag())
	{
	/* these objects do not refer to other objects at all */
	case FLOAT_TYPE:
	case BYTE_ARRAY_TYPE:
	case BIGNUM_TYPE:
	case CALLSTACK_TYPE:
		return 0;
	/* these objects have some binary data at the end */
	case WORD_TYPE:
		return sizeof(word) - sizeof(cell) * 3;
	case ALIEN_TYPE:
		return sizeof(cell) * 3;
	case DLL_TYPE:
		return sizeof(cell) * 2;
	case QUOTATION_TYPE:
		return sizeof(quotation) - sizeof(cell) * 2;
	case STRING_TYPE:
		return sizeof(string);
	/* everything else consists entirely of pointers */
	case ARRAY_TYPE:
		return array_size<array>(array_capacity((array*)this));
	case TUPLE_TYPE:
		return tuple_size(untag<tuple_layout>(((tuple *)this)->layout));
	case WRAPPER_TYPE:
		return sizeof(wrapper);
	default:
		critical_error("Invalid header",(cell)this);
                return 0; /* can't happen */
	}
}

data_heap_room factor_vm::data_room()
{
	data_heap_room room;

	room.nursery_size             = nursery.size;
	room.nursery_occupied         = nursery.occupied_space();
	room.nursery_free             = nursery.free_space();
	room.aging_size               = data->aging->size;
	room.aging_occupied           = data->aging->occupied_space();
	room.aging_free               = data->aging->free_space();
	room.tenured_size             = data->tenured->size;
	room.tenured_occupied         = data->tenured->occupied_space();
	room.tenured_total_free       = data->tenured->free_space();
	room.tenured_contiguous_free  = data->tenured->largest_free_block();
	room.tenured_free_block_count = data->tenured->free_block_count();
	room.cards                    = data->cards_end - data->cards;
	room.decks                    = data->decks_end - data->decks;
	room.mark_stack               = data->tenured->mark_stack.capacity();

	return room;
}

void factor_vm::primitive_data_room()
{
	data_heap_room room = data_room();
	dpush(tag<byte_array>(byte_array_from_value(&room)));
}

struct object_accumulator {
	cell type;
	std::vector<cell> objects;

	explicit object_accumulator(cell type_) : type(type_) {}

	void operator()(object *obj)
	{
		if(type == TYPE_COUNT || obj->h.hi_tag() == type)
			objects.push_back(tag_dynamic(obj));
	}
};

cell factor_vm::instances(cell type)
{
	object_accumulator accum(type);
	each_object(accum);
	cell object_count = accum.objects.size();

	data_roots.push_back((cell)&accum.objects[0]);
	data_roots.push_back(object_count);

	array *objects = allot_array(object_count,false_object);
	memcpy(objects->data(),&accum.objects[0],object_count * sizeof(cell));

	data_roots.pop_back();
	data_roots.pop_back();

	return tag<array>(objects);
}

void factor_vm::primitive_all_instances()
{
	primitive_full_gc();
	dpush(instances(TYPE_COUNT));
}

cell factor_vm::find_all_words()
{
	return instances(WORD_TYPE);
}

}
<commit_msg>vm: report true size of mark stack<commit_after>#include "master.hpp"

namespace factor
{

void factor_vm::init_card_decks()
{
	cards_offset = (cell)data->cards - addr_to_card(data->start);
	decks_offset = (cell)data->decks - addr_to_deck(data->start);
}

data_heap::data_heap(cell young_size_,
	cell aging_size_,
	cell tenured_size_)
{
	young_size_ = align(young_size_,deck_size);
	aging_size_ = align(aging_size_,deck_size);
	tenured_size_ = align(tenured_size_,deck_size);

	young_size = young_size_;
	aging_size = aging_size_;
	tenured_size = tenured_size_;

	cell total_size = young_size + 2 * aging_size + tenured_size + deck_size;
	seg = new segment(total_size,false);

	cell cards_size = addr_to_card(total_size);
	cards = new card[cards_size];
	cards_end = cards + cards_size;
	memset(cards,0,cards_size);

	cell decks_size = addr_to_deck(total_size);
	decks = new card_deck[decks_size];
	decks_end = decks + decks_size;
	memset(decks,0,decks_size);

	start = align(seg->start,deck_size);

	tenured = new tenured_space(tenured_size,start);

	aging = new aging_space(aging_size,tenured->end);
	aging_semispace = new aging_space(aging_size,aging->end);

	nursery = new nursery_space(young_size,aging_semispace->end);

	assert(seg->end - nursery->end <= deck_size);
}

data_heap::~data_heap()
{
	delete seg;
	delete nursery;
	delete aging;
	delete aging_semispace;
	delete tenured;
	delete[] cards;
	delete[] decks;
}

data_heap *data_heap::grow(cell requested_bytes)
{
	cell new_tenured_size = (tenured_size * 2) + requested_bytes;
	return new data_heap(young_size,
		aging_size,
		new_tenured_size);
}

template<typename Generation> void data_heap::clear_cards(Generation *gen)
{
	cell first_card = addr_to_card(gen->start - start);
	cell last_card = addr_to_card(gen->end - start);
	memset(&cards[first_card],0,last_card - first_card);
}

template<typename Generation> void data_heap::clear_decks(Generation *gen)
{
	cell first_deck = addr_to_deck(gen->start - start);
	cell last_deck = addr_to_deck(gen->end - start);
	memset(&decks[first_deck],0,last_deck - first_deck);
}

void data_heap::reset_generation(nursery_space *gen)
{
	gen->here = gen->start;
}

void data_heap::reset_generation(aging_space *gen)
{
	gen->here = gen->start;
	clear_cards(gen);
	clear_decks(gen);
	gen->starts.clear_object_start_offsets();
}

void data_heap::reset_generation(tenured_space *gen)
{
	clear_cards(gen);
	clear_decks(gen);
}

bool data_heap::low_memory_p()
{
	return (tenured->free_space() <= nursery->size + aging->size);
}

void data_heap::mark_all_cards()
{
	memset(cards,-1,cards_end - cards);
	memset(decks,-1,decks_end - decks);
}

void factor_vm::set_data_heap(data_heap *data_)
{
	data = data_;
	nursery = *data->nursery;
	init_card_decks();
}

void factor_vm::init_data_heap(cell young_size, cell aging_size, cell tenured_size)
{
	set_data_heap(new data_heap(young_size,aging_size,tenured_size));
}

/* Size of the object pointed to by an untagged pointer */
cell object::size() const
{
	if(free_p()) return ((free_heap_block *)this)->size();

	switch(h.hi_tag())
	{
	case ARRAY_TYPE:
		return align(array_size((array*)this),data_alignment);
	case BIGNUM_TYPE:
		return align(array_size((bignum*)this),data_alignment);
	case BYTE_ARRAY_TYPE:
		return align(array_size((byte_array*)this),data_alignment);
	case STRING_TYPE:
		return align(string_size(string_capacity((string*)this)),data_alignment);
	case TUPLE_TYPE:
		{
			tuple_layout *layout = (tuple_layout *)UNTAG(((tuple *)this)->layout);
			return align(tuple_size(layout),data_alignment);
		}
	case QUOTATION_TYPE:
		return align(sizeof(quotation),data_alignment);
	case WORD_TYPE:
		return align(sizeof(word),data_alignment);
	case FLOAT_TYPE:
		return align(sizeof(boxed_float),data_alignment);
	case DLL_TYPE:
		return align(sizeof(dll),data_alignment);
	case ALIEN_TYPE:
		return align(sizeof(alien),data_alignment);
	case WRAPPER_TYPE:
		return align(sizeof(wrapper),data_alignment);
	case CALLSTACK_TYPE:
		return align(callstack_size(untag_fixnum(((callstack *)this)->length)),data_alignment);
	default:
		critical_error("Invalid header",(cell)this);
		return 0; /* can't happen */
	}
}

/* The number of cells from the start of the object which should be scanned by
the GC. Some types have a binary payload at the end (string, word, DLL) which
we ignore. */
cell object::binary_payload_start() const
{
	switch(h.hi_tag())
	{
	/* these objects do not refer to other objects at all */
	case FLOAT_TYPE:
	case BYTE_ARRAY_TYPE:
	case BIGNUM_TYPE:
	case CALLSTACK_TYPE:
		return 0;
	/* these objects have some binary data at the end */
	case WORD_TYPE:
		return sizeof(word) - sizeof(cell) * 3;
	case ALIEN_TYPE:
		return sizeof(cell) * 3;
	case DLL_TYPE:
		return sizeof(cell) * 2;
	case QUOTATION_TYPE:
		return sizeof(quotation) - sizeof(cell) * 2;
	case STRING_TYPE:
		return sizeof(string);
	/* everything else consists entirely of pointers */
	case ARRAY_TYPE:
		return array_size<array>(array_capacity((array*)this));
	case TUPLE_TYPE:
		return tuple_size(untag<tuple_layout>(((tuple *)this)->layout));
	case WRAPPER_TYPE:
		return sizeof(wrapper);
	default:
		critical_error("Invalid header",(cell)this);
                return 0; /* can't happen */
	}
}

data_heap_room factor_vm::data_room()
{
	data_heap_room room;

	room.nursery_size             = nursery.size;
	room.nursery_occupied         = nursery.occupied_space();
	room.nursery_free             = nursery.free_space();
	room.aging_size               = data->aging->size;
	room.aging_occupied           = data->aging->occupied_space();
	room.aging_free               = data->aging->free_space();
	room.tenured_size             = data->tenured->size;
	room.tenured_occupied         = data->tenured->occupied_space();
	room.tenured_total_free       = data->tenured->free_space();
	room.tenured_contiguous_free  = data->tenured->largest_free_block();
	room.tenured_free_block_count = data->tenured->free_block_count();
	room.cards                    = data->cards_end - data->cards;
	room.decks                    = data->decks_end - data->decks;
	room.mark_stack               = data->tenured->mark_stack.capacity() * sizeof(cell);

	return room;
}

void factor_vm::primitive_data_room()
{
	data_heap_room room = data_room();
	dpush(tag<byte_array>(byte_array_from_value(&room)));
}

struct object_accumulator {
	cell type;
	std::vector<cell> objects;

	explicit object_accumulator(cell type_) : type(type_) {}

	void operator()(object *obj)
	{
		if(type == TYPE_COUNT || obj->h.hi_tag() == type)
			objects.push_back(tag_dynamic(obj));
	}
};

cell factor_vm::instances(cell type)
{
	object_accumulator accum(type);
	each_object(accum);
	cell object_count = accum.objects.size();

	data_roots.push_back((cell)&accum.objects[0]);
	data_roots.push_back(object_count);

	array *objects = allot_array(object_count,false_object);
	memcpy(objects->data(),&accum.objects[0],object_count * sizeof(cell));

	data_roots.pop_back();
	data_roots.pop_back();

	return tag<array>(objects);
}

void factor_vm::primitive_all_instances()
{
	primitive_full_gc();
	dpush(instances(TYPE_COUNT));
}

cell factor_vm::find_all_words()
{
	return instances(WORD_TYPE);
}

}
<|endoftext|>


<commit_before>#include "Id.hpp"

namespace Dissent {
namespace Connections {
  const Id Id::Zero = Id(Integer(long(0)));

  Id::Id()
  {
    CryptoPP::AutoSeededX917RNG<CryptoPP::DES_EDE3> rng;
    Integer iid(rng, Id::BitSize);
    QByteArray bid = Id::GetQByteArray(iid);
    Init(bid, iid, Id::GetQString(bid));
  }

  Id::Id(const QByteArray &bid)
  {
    Init(bid, Id::GetInteger(bid), Id::GetQString(bid));
  }

  Id::Id(const Integer &iid)
  {
    QByteArray bid = Id::GetQByteArray(iid);
    Init(bid, iid, Id::GetQString(bid));
  }

  Id::Id(const QString &sid)
  {
    QByteArray bid = Id::GetQByteArray(sid);
    Init(bid, Id::GetInteger(bid), sid);
  }

  void Id::Init(const QByteArray &bid, const Integer &iid, const QString &sid)
  {
    if(iid.BitCount() > BitSize) {
      throw std::runtime_error("Bitsize too large: " + iid.BitCount());
    }

    _data = QExplicitlySharedDataPointer<IdData>(new IdData(bid, iid, sid));
  }

  QString Id::ToString() const
  {
    return _data->sid;
  }

  bool Id::operator==(const Id &other) const
  {
    return _data->iid == other._data->iid;
  }

  bool Id::operator!=(const Id &other) const
  {
    return _data->iid != other._data->iid;
  }

  bool Id::operator<(const Id &other) const
  {
    return _data->iid < other._data->iid;
  }

  bool Id::operator>(const Id &other) const
  {
    return _data->iid > other._data->iid;
  }

  inline const QByteArray Id::GetQByteArray(const Integer &iid)
  {
    QByteArray bid(20, 0);
    iid.Encode(reinterpret_cast<byte *>(bid.data()), ByteSize);
    return bid;
  }

  inline const QByteArray Id::GetQByteArray(const QString &sid)
  {
    QByteArray bid = QByteArray::fromBase64(sid.toLocal8Bit()).data();
    return bid;
  }

  inline const Integer Id::GetInteger(const QByteArray &bid)
  {
    Integer iid(reinterpret_cast<const byte *>(bid.data()), ByteSize);
    return iid;
  }

  inline const QString Id::GetQString(const QByteArray &bid)
  {
    QString sid(bid.toBase64());
    return sid;
  }
}
}
<commit_msg>[Connections] No need t explicitly make it a QSharedDataPointer<commit_after>#include "Id.hpp"

namespace Dissent {
namespace Connections {
  const Id Id::Zero = Id(Integer(long(0)));

  Id::Id()
  {
    CryptoPP::AutoSeededX917RNG<CryptoPP::DES_EDE3> rng;
    Integer iid(rng, Id::BitSize);
    QByteArray bid = Id::GetQByteArray(iid);
    Init(bid, iid, Id::GetQString(bid));
  }

  Id::Id(const QByteArray &bid)
  {
    Init(bid, Id::GetInteger(bid), Id::GetQString(bid));
  }

  Id::Id(const Integer &iid)
  {
    QByteArray bid = Id::GetQByteArray(iid);
    Init(bid, iid, Id::GetQString(bid));
  }

  Id::Id(const QString &sid)
  {
    QByteArray bid = Id::GetQByteArray(sid);
    Init(bid, Id::GetInteger(bid), sid);
  }

  void Id::Init(const QByteArray &bid, const Integer &iid, const QString &sid)
  {
    if(iid.BitCount() > BitSize) {
      throw std::runtime_error("Bitsize too large: " + iid.BitCount());
    }

    _data = new IdData(bid, iid, sid);
  }

  QString Id::ToString() const
  {
    return _data->sid;
  }

  bool Id::operator==(const Id &other) const
  {
    return _data->iid == other._data->iid;
  }

  bool Id::operator!=(const Id &other) const
  {
    return _data->iid != other._data->iid;
  }

  bool Id::operator<(const Id &other) const
  {
    return _data->iid < other._data->iid;
  }

  bool Id::operator>(const Id &other) const
  {
    return _data->iid > other._data->iid;
  }

  inline const QByteArray Id::GetQByteArray(const Integer &iid)
  {
    QByteArray bid(20, 0);
    iid.Encode(reinterpret_cast<byte *>(bid.data()), ByteSize);
    return bid;
  }

  inline const QByteArray Id::GetQByteArray(const QString &sid)
  {
    QByteArray bid = QByteArray::fromBase64(sid.toLocal8Bit()).data();
    return bid;
  }

  inline const Integer Id::GetInteger(const QByteArray &bid)
  {
    Integer iid(reinterpret_cast<const byte *>(bid.data()), ByteSize);
    return iid;
  }

  inline const QString Id::GetQString(const QByteArray &bid)
  {
    QString sid(bid.toBase64());
    return sid;
  }
}
}
<|endoftext|>


<commit_before>/*
 * Copyright(c) Records For Living, Inc. 2004-2011.  All rights reserved
 */
#include	"Stroika/Foundation/StroikaPreComp.h"

#include	<iostream>

#include	"Stroika/Foundation/Characters/CodePage.h"
#include	"Stroika/Foundation/Containers/Common.h"
#include	"Stroika/Foundation/Debug/Assertions.h"
#include	"Stroika/Foundation/Debug/Debugger.h"
#include	"Stroika/Foundation/Execution/StringException.h"

#include	"TestHarness.h"

using	namespace	Stroika;
using	namespace	Stroika::Foundation;
using	namespace	Stroika::TestHarness;

namespace	{
	void	_ASSERT_HANDLER_ (const char* assertCategory, const char* assertionText, const char* fileName, int lineNum, const char* functionName)
		{
			if (assertCategory == nullptr) {
				assertCategory = "Unknown assertion";
			}
			if (assertionText == nullptr) {
				assertionText = "";
			}
			if (functionName == nullptr) {
				functionName = "";
			}
			cerr << "FAILED: " << assertCategory << "; " << assertionText << ";" << functionName << ";" << fileName << ": " << lineNum << endl;

			Debug::DropIntoDebuggerIfPresent ();

			_exit (EXIT_FAILURE);
		}
	void	_TerminateHandler_ ()
		{
			cerr << "FAILED: _TerminateHandler_ called" << endl;
			Debug::DropIntoDebuggerIfPresent ();
			_exit (EXIT_FAILURE);
		}
}

void	TestHarness::Setup ()
{
#if		qDebug
	Stroika::Foundation::Debug::SetAssertionHandler (_ASSERT_HANDLER_);
#endif
	set_terminate (_TerminateHandler_);
}

void	TestHarness::PrintPassOrFail (void (*regressionTest) ())
{
	try {
		(*regressionTest) ();
		cout << "Succeeded" << endl;
	}
	catch (const std::exception& e) {
		cerr << "FAILED: REGRESSION TEST (std::exception): '" << e.what () << endl;
		cout << "Failed" << endl;
		Debug::DropIntoDebuggerIfPresent ();
		_exit (EXIT_FAILURE);
	}
	catch (Execution::StringException& e) {
		cerr << "FAILED: REGRESSION TEST (Execution::StringException): '" << Characters::WideStringToNarrowSDKString (e.As<wstring> ()) << endl;
		cout << "Failed" << endl;
		Debug::DropIntoDebuggerIfPresent ();
		_exit (EXIT_FAILURE);
	}
	catch (...) {
		cerr << "FAILED: REGRESSION TEST EXCEPTION" << endl;
		cout << "Failed" << endl;
		Debug::DropIntoDebuggerIfPresent ();
		_exit (EXIT_FAILURE);
	}
}

void	TestHarness::Test_ (bool failIfFalse, const char* regressionTestText, const char* fileName, int lineNum)
{
	if (not failIfFalse) {
		_ASSERT_HANDLER_ ("RegressionTestFailure", regressionTestText, fileName, lineNum, "");
	}
}
<commit_msg>set unexpected hanlder on automated test suite (so we get better error message)<commit_after>/*
 * Copyright(c) Records For Living, Inc. 2004-2011.  All rights reserved
 */
#include	"Stroika/Foundation/StroikaPreComp.h"

#include	<iostream>

#include	"Stroika/Foundation/Characters/CodePage.h"
#include	"Stroika/Foundation/Containers/Common.h"
#include	"Stroika/Foundation/Debug/Assertions.h"
#include	"Stroika/Foundation/Debug/Debugger.h"
#include	"Stroika/Foundation/Execution/StringException.h"

#include	"TestHarness.h"

using	namespace	Stroika;
using	namespace	Stroika::Foundation;
using	namespace	Stroika::TestHarness;

namespace	{
	void	_ASSERT_HANDLER_ (const char* assertCategory, const char* assertionText, const char* fileName, int lineNum, const char* functionName)
		{
			if (assertCategory == nullptr) {
				assertCategory = "Unknown assertion";
			}
			if (assertionText == nullptr) {
				assertionText = "";
			}
			if (functionName == nullptr) {
				functionName = "";
			}
			cerr << "FAILED: " << assertCategory << "; " << assertionText << ";" << functionName << ";" << fileName << ": " << lineNum << endl;

			Debug::DropIntoDebuggerIfPresent ();

			_exit (EXIT_FAILURE);
		}
	void	_TerminateHandler_ ()
		{
			cerr << "FAILED: _TerminateHandler_ called" << endl;
			Debug::DropIntoDebuggerIfPresent ();
			_exit (EXIT_FAILURE);
		}
	void	_UnexpectedHandler_ ()
		{
			cerr << "FAILED: _UnexpectedHandler_ called" << endl;
			Debug::DropIntoDebuggerIfPresent ();
			_exit (EXIT_FAILURE);
		}
}

void	TestHarness::Setup ()
{
#if		qDebug
	Stroika::Foundation::Debug::SetAssertionHandler (_ASSERT_HANDLER_);
#endif
	set_terminate (_TerminateHandler_);
	set_unexpected (_UnexpectedHandler_);
}

void	TestHarness::PrintPassOrFail (void (*regressionTest) ())
{
	try {
		(*regressionTest) ();
		cout << "Succeeded" << endl;
	}
	catch (const std::exception& e) {
		cerr << "FAILED: REGRESSION TEST (std::exception): '" << e.what () << endl;
		cout << "Failed" << endl;
		Debug::DropIntoDebuggerIfPresent ();
		_exit (EXIT_FAILURE);
	}
	catch (Execution::StringException& e) {
		cerr << "FAILED: REGRESSION TEST (Execution::StringException): '" << Characters::WideStringToNarrowSDKString (e.As<wstring> ()) << endl;
		cout << "Failed" << endl;
		Debug::DropIntoDebuggerIfPresent ();
		_exit (EXIT_FAILURE);
	}
	catch (...) {
		cerr << "FAILED: REGRESSION TEST EXCEPTION" << endl;
		cout << "Failed" << endl;
		Debug::DropIntoDebuggerIfPresent ();
		_exit (EXIT_FAILURE);
	}
}

void	TestHarness::Test_ (bool failIfFalse, const char* regressionTestText, const char* fileName, int lineNum)
{
	if (not failIfFalse) {
		_ASSERT_HANDLER_ ("RegressionTestFailure", regressionTestText, fileName, lineNum, "");
	}
}
<|endoftext|>


<commit_before>/*
 * GridMapVisual.cpp
 *
 *  Created on: Aug 3, 2016
 *  Author: Philipp Krüsi, Péter Fankhauser
 *  Institute: ETH Zurich, Autonomous Systems Lab
 */

#include <rviz/uniform_string_stream.h>
#include <OGRE/OgreMaterialManager.h>
#include <OGRE/OgreTextureManager.h>
#include <OGRE/OgreTechnique.h>

#include <OGRE/OgreVector3.h>
#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreSceneManager.h>
#include <OGRE/OgreManualObject.h>

#include <rviz/ogre_helpers/billboard_line.h>

#include <grid_map_ros/grid_map_ros.hpp>
#include <grid_map_core/GridMapMath.hpp>
#include "grid_map_rviz_plugin/GridMapVisual.hpp"

namespace grid_map_rviz_plugin {

GridMapVisual::GridMapVisual(Ogre::SceneManager* sceneManager, Ogre::SceneNode* parentNode)
    : manualObject_(0),
      haveMap_(false)
{
  sceneManager_ = sceneManager;
  frameNode_ = parentNode->createChildSceneNode();

  // Create BillboardLine object.
  meshLines_.reset(new rviz::BillboardLine(sceneManager_, frameNode_));
}

GridMapVisual::~GridMapVisual()
{
  // Destroy the ManualObject.
  sceneManager_->destroyManualObject(manualObject_);
  material_->unload();
  Ogre::MaterialManager::getSingleton().remove(material_->getName());

  // Destroy the frame node.
  sceneManager_->destroySceneNode(frameNode_);
}

void GridMapVisual::setMessage(const grid_map_msgs::GridMap::ConstPtr& msg)
{
  // Convert grid map message.
  grid_map::GridMapRosConverter::fromMessage(*msg, map_);
  haveMap_ = true;
}

void GridMapVisual::computeVisualization(float alpha, bool showGridLines, bool flatTerrain,
                                         std::string heightLayer, bool flatColor,
                                         Ogre::ColourValue meshColor,
					 bool mapLayerColor, std::string colorLayer,
                                         bool useRainbow, bool invertRainbow,
					 Ogre::ColourValue minColor, Ogre::ColourValue maxColor,
					 bool autocomputeIntensity,
                                         float minIntensity, float maxIntensity)
{
  if (!haveMap_) {
    ROS_DEBUG("Unable to visualize grid map, no map data. Use setMessage() first!");
    return;
  }

  // Get list of layers and check if the requested ones are present.
  std::vector<std::string> layerNames = map_.getLayers();
  if (layerNames.size() < 1) {
    ROS_DEBUG("Unable to visualize grid map, map must contain at least one layer.");
    return;
  }
  if ((!flatTerrain && !map_.exists(heightLayer)) || (!flatColor && !map_.exists(colorLayer))) {
    ROS_DEBUG("Unable to visualize grid map, requested layer(s) not available.");
    return;
  }

  // Convert to simple format, makes things easier.
  map_.convertToDefaultStartIndex();

  // basic grid map data
  size_t rows = map_.getSize()(0);
  size_t cols = map_.getSize()(1);
  if (rows < 2 || cols < 2) {
    ROS_DEBUG("GridMap has not enough cells.");
    return;
  }
  double resolution = map_.getResolution();
  const grid_map::Matrix& heightData = map_[flatTerrain ? layerNames[0] : heightLayer];
  const grid_map::Matrix& colorData = map_[flatColor ? layerNames[0] : colorLayer];

  // initialize ManualObject
  if (!manualObject_) {
    static uint32_t count = 0;
    rviz::UniformStringStream ss;
    ss << "Mesh" << count++;
    manualObject_ = sceneManager_->createManualObject(ss.str());
    frameNode_->attachObject(manualObject_);

    ss << "Material";
    materialName_ = ss.str();
    material_ = Ogre::MaterialManager::getSingleton().create(materialName_, "rviz");
    material_->setReceiveShadows(false);
    material_->getTechnique(0)->setLightingEnabled(true);
    material_->setCullingMode(Ogre::CULL_NONE);
  }

  manualObject_->clear();
  size_t nVertices = 4 + 6 * (cols * rows - cols - rows);
  manualObject_->estimateVertexCount(nVertices);
  manualObject_->begin(materialName_, Ogre::RenderOperation::OT_TRIANGLE_LIST);

  meshLines_->clear();
  if (showGridLines) {
    meshLines_->setColor(0.0, 0.0, 0.0, alpha);
    meshLines_->setLineWidth(resolution / 10.0);
    meshLines_->setMaxPointsPerLine(2);
    size_t nLines = rows * (cols - 1) + cols * (rows - 1);
    meshLines_->setNumLines(nLines);
  }

  // Determine max and min intensity.
  if (autocomputeIntensity && !flatColor && !mapLayerColor) {
    minIntensity = colorData.minCoeffOfFinites();
    maxIntensity = colorData.maxCoeffOfFinites();
  }

  if (!map_.hasBasicLayers()) map_.setBasicLayers({heightLayer});

  // Plot mesh.
  for (size_t i = 0; i < rows - 1; ++i) {
    for (size_t j = 0; j < cols - 1; ++j) {
      std::vector<Ogre::Vector3> vertices;
      std::vector<Ogre::ColourValue> colors;
      for (size_t k = 0; k < 2; k++) {
        for (size_t l = 0; l < 2; l++) {
          grid_map::Position position;
          grid_map::Index index(i + k, j + l);
          if (!map_.isValid(index)) continue;

          map_.getPosition(index, position);
          float height = heightData(index(0), index(1));
          vertices.push_back(Ogre::Vector3(position(0), position(1), flatTerrain ? 0.0 : height));
          if (!flatColor) {
            float color = colorData(index(0), index(1));
            Ogre::ColourValue colorValue;
            if (mapLayerColor) {
              Eigen::Vector3f colorVectorRGB;
              grid_map::colorValueToVector(color, colorVectorRGB);
              colorValue = Ogre::ColourValue(colorVectorRGB(0), colorVectorRGB(1), colorVectorRGB(2));
            } else {
              normalizeIntensity(color, minIntensity, maxIntensity);
              colorValue = useRainbow ? (invertRainbow ? getRainbowColor(1.0f - color)
                                                       : getRainbowColor(color))
                                      : getInterpolatedColor(color, minColor, maxColor);
            }
            colors.push_back(colorValue);
          }
        }
      }

      // Plot triangles if we have enough vertices
      if (vertices.size() > 2) {
        Ogre::Vector3 normal = vertices.size() == 4
                               ? (vertices[3] - vertices[0]).crossProduct(vertices[2] -vertices[1])
                               : (vertices[2] - vertices[1]).crossProduct(vertices[1] - vertices[0]);
        normal.normalise();
        // Create one or two triangles from the vertices depending on how many vertices we have
        for (size_t m = 1; m < vertices.size() - 1; m++) {
          manualObject_->position(vertices[m-1]);
          manualObject_->normal(normal);
          Ogre::ColourValue color = flatColor ? meshColor : colors[m-1];
          manualObject_->colour(color.r, color.g, color.b, alpha);

          manualObject_->position(vertices[m]);
          manualObject_->normal(normal);
          color = flatColor ? meshColor : colors[m];
          manualObject_->colour(color.r, color.g, color.b, alpha);

          manualObject_->position(vertices[m+1]);
          manualObject_->normal(normal);
          color = flatColor ? meshColor : colors[m+1];
          manualObject_->colour(color.r, color.g, color.b, alpha);
        }

        // plot grid lines
        if (showGridLines) {
          meshLines_->addPoint(vertices[0]);
          meshLines_->addPoint(vertices[1]);
          meshLines_->newLine();

          if (vertices.size() == 3) {
            meshLines_->addPoint(vertices[1]);
            meshLines_->addPoint(vertices[2]);
            meshLines_->newLine();
          } else {
            meshLines_->addPoint(vertices[1]);
            meshLines_->addPoint(vertices[3]);
            meshLines_->newLine();

            meshLines_->addPoint(vertices[3]);
            meshLines_->addPoint(vertices[2]);
            meshLines_->newLine();
          }

          meshLines_->addPoint(vertices[2]);
          meshLines_->addPoint(vertices[0]);
          meshLines_->newLine();
        }
      }
    }
  }

  manualObject_->end();
  material_->getTechnique(0)->setLightingEnabled(false);

  if (alpha < 0.9998) {
    material_->getTechnique(0)->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
    material_->getTechnique(0)->setDepthWriteEnabled(false);
  } else {
    material_->getTechnique(0)->setSceneBlending(Ogre::SBT_REPLACE);
    material_->getTechnique(0)->setDepthWriteEnabled(true);
  }
}

void GridMapVisual::setFramePosition(const Ogre::Vector3& position)
{
  frameNode_->setPosition(position);
}

void GridMapVisual::setFrameOrientation(const Ogre::Quaternion& orientation)
{
  frameNode_->setOrientation(orientation);
}

std::vector<std::string> GridMapVisual::getLayerNames()
{
  return map_.getLayers();
}

// Compute intensity value in the interval [0,1].
void GridMapVisual::normalizeIntensity(float& intensity, float min_intensity, float max_intensity)
{
  intensity = std::min(intensity, max_intensity);
  intensity = std::max(intensity, min_intensity);
  intensity = (intensity - min_intensity) / (max_intensity - min_intensity);
}

// Copied from rviz/src/rviz/default_plugin/point_cloud_transformers.cpp.
Ogre::ColourValue GridMapVisual::getRainbowColor(float intensity)
{
  intensity = std::min(intensity, 1.0f);
  intensity = std::max(intensity, 0.0f);

  float h = intensity * 5.0f + 1.0f;
  int i = floor(h);
  float f = h - i;
  if (!(i & 1)) f = 1 - f;  // if i is even
  float n = 1 - f;

  Ogre::ColourValue color;
  if (i <= 1) color[0] = n, color[1] = 0, color[2] = 1;
  else if (i == 2) color[0] = 0, color[1] = n, color[2] = 1;
  else if (i == 3) color[0] = 0, color[1] = 1, color[2] = n;
  else if (i == 4) color[0] = n, color[1] = 1, color[2] = 0;
  else if (i >= 5) color[0] = 1, color[1] = n, color[2] = 0;

  return color;
}

// Get interpolated color value.
Ogre::ColourValue GridMapVisual::getInterpolatedColor(float intensity, Ogre::ColourValue min_color,
                                                      Ogre::ColourValue max_color)
{
  intensity = std::min(intensity, 1.0f);
  intensity = std::max(intensity, 0.0f);

  Ogre::ColourValue color;
  color.r = intensity * (max_color.r - min_color.r) + min_color.r;
  color.g = intensity * (max_color.g - min_color.g) + min_color.g;
  color.b = intensity * (max_color.b - min_color.b) + min_color.b;

  return color;
}

}  // namespace
<commit_msg>Fixes error in grid_map_rviz_plugin when rendering lines.<commit_after>/*
 * GridMapVisual.cpp
 *
 *  Created on: Aug 3, 2016
 *  Author: Philipp Krüsi, Péter Fankhauser
 *  Institute: ETH Zurich, Autonomous Systems Lab
 */

#include <rviz/uniform_string_stream.h>
#include <OGRE/OgreMaterialManager.h>
#include <OGRE/OgreTextureManager.h>
#include <OGRE/OgreTechnique.h>

#include <OGRE/OgreVector3.h>
#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreSceneManager.h>
#include <OGRE/OgreManualObject.h>

#include <rviz/ogre_helpers/billboard_line.h>

#include <grid_map_ros/grid_map_ros.hpp>
#include <grid_map_core/GridMapMath.hpp>
#include "grid_map_rviz_plugin/GridMapVisual.hpp"

namespace grid_map_rviz_plugin {

GridMapVisual::GridMapVisual(Ogre::SceneManager* sceneManager, Ogre::SceneNode* parentNode)
    : manualObject_(0),
      haveMap_(false)
{
  sceneManager_ = sceneManager;
  frameNode_ = parentNode->createChildSceneNode();

  // Create BillboardLine object.
  meshLines_.reset(new rviz::BillboardLine(sceneManager_, frameNode_));
}

GridMapVisual::~GridMapVisual()
{
  // Destroy the ManualObject.
  sceneManager_->destroyManualObject(manualObject_);
  material_->unload();
  Ogre::MaterialManager::getSingleton().remove(material_->getName());

  // Destroy the frame node.
  sceneManager_->destroySceneNode(frameNode_);
}

void GridMapVisual::setMessage(const grid_map_msgs::GridMap::ConstPtr& msg)
{
  // Convert grid map message.
  grid_map::GridMapRosConverter::fromMessage(*msg, map_);
  haveMap_ = true;
}

void GridMapVisual::computeVisualization(float alpha, bool showGridLines, bool flatTerrain,
                                         std::string heightLayer, bool flatColor,
                                         Ogre::ColourValue meshColor,
					 bool mapLayerColor, std::string colorLayer,
                                         bool useRainbow, bool invertRainbow,
					 Ogre::ColourValue minColor, Ogre::ColourValue maxColor,
					 bool autocomputeIntensity,
                                         float minIntensity, float maxIntensity)
{
  if (!haveMap_) {
    ROS_DEBUG("Unable to visualize grid map, no map data. Use setMessage() first!");
    return;
  }

  // Get list of layers and check if the requested ones are present.
  std::vector<std::string> layerNames = map_.getLayers();
  if (layerNames.size() < 1) {
    ROS_DEBUG("Unable to visualize grid map, map must contain at least one layer.");
    return;
  }
  if ((!flatTerrain && !map_.exists(heightLayer)) || (!flatColor && !map_.exists(colorLayer))) {
    ROS_DEBUG("Unable to visualize grid map, requested layer(s) not available.");
    return;
  }

  // Convert to simple format, makes things easier.
  map_.convertToDefaultStartIndex();

  // Basic grid map data.
  const size_t rows = map_.getSize()(0);
  const size_t cols = map_.getSize()(1);
  if (rows < 2 || cols < 2) {
    ROS_DEBUG("GridMap has not enough cells.");
    return;
  }
  const double resolution = map_.getResolution();
  const grid_map::Matrix& heightData = map_[flatTerrain ? layerNames[0] : heightLayer];
  const grid_map::Matrix& colorData = map_[flatColor ? layerNames[0] : colorLayer];

  // initialize ManualObject
  if (!manualObject_) {
    static uint32_t count = 0;
    rviz::UniformStringStream ss;
    ss << "Mesh" << count++;
    manualObject_ = sceneManager_->createManualObject(ss.str());
    frameNode_->attachObject(manualObject_);

    ss << "Material";
    materialName_ = ss.str();
    material_ = Ogre::MaterialManager::getSingleton().create(materialName_, "rviz");
    material_->setReceiveShadows(false);
    material_->getTechnique(0)->setLightingEnabled(true);
    material_->setCullingMode(Ogre::CULL_NONE);
  }

  manualObject_->clear();
  size_t nVertices = 4 + 6 * (cols * rows - cols - rows);
  manualObject_->estimateVertexCount(nVertices);
  manualObject_->begin(materialName_, Ogre::RenderOperation::OT_TRIANGLE_LIST);

  meshLines_->clear();
  if (showGridLines) {
    meshLines_->setColor(0.0, 0.0, 0.0, alpha);
    meshLines_->setLineWidth(resolution / 10.0);
    meshLines_->setMaxPointsPerLine(2);
    // In the algorithm below, we have to account for max. 4 lines per cell.
    size_t nLines = 2 * (rows * (cols - 1) + cols * (rows - 1));
    meshLines_->setNumLines(nLines);
  }

  // Determine max and min intensity.
  if (autocomputeIntensity && !flatColor && !mapLayerColor) {
    minIntensity = colorData.minCoeffOfFinites();
    maxIntensity = colorData.maxCoeffOfFinites();
  }

  if (!map_.hasBasicLayers()) map_.setBasicLayers({heightLayer});

  // Plot mesh.
  for (size_t i = 0; i < rows - 1; ++i) {
    for (size_t j = 0; j < cols - 1; ++j) {
      std::vector<Ogre::Vector3> vertices;
      std::vector<Ogre::ColourValue> colors;
      for (size_t k = 0; k < 2; k++) {
        for (size_t l = 0; l < 2; l++) {
          grid_map::Position position;
          grid_map::Index index(i + k, j + l);
          if (!map_.isValid(index)) continue;

          map_.getPosition(index, position);
          float height = heightData(index(0), index(1));
          vertices.push_back(Ogre::Vector3(position(0), position(1), flatTerrain ? 0.0 : height));
          if (!flatColor) {
            float color = colorData(index(0), index(1));
            Ogre::ColourValue colorValue;
            if (mapLayerColor) {
              Eigen::Vector3f colorVectorRGB;
              grid_map::colorValueToVector(color, colorVectorRGB);
              colorValue = Ogre::ColourValue(colorVectorRGB(0), colorVectorRGB(1), colorVectorRGB(2));
            } else {
              normalizeIntensity(color, minIntensity, maxIntensity);
              colorValue = useRainbow ? (invertRainbow ? getRainbowColor(1.0f - color)
                                                       : getRainbowColor(color))
                                      : getInterpolatedColor(color, minColor, maxColor);
            }
            colors.push_back(colorValue);
          }
        }
      }

      // Plot triangles if we have enough vertices.
      if (vertices.size() > 2) {
        Ogre::Vector3 normal = vertices.size() == 4
                               ? (vertices[3] - vertices[0]).crossProduct(vertices[2] -vertices[1])
                               : (vertices[2] - vertices[1]).crossProduct(vertices[1] - vertices[0]);
        normal.normalise();
        // Create one or two triangles from the vertices depending on how many vertices we have.
        for (size_t m = 1; m < vertices.size() - 1; m++) {
          manualObject_->position(vertices[m-1]);
          manualObject_->normal(normal);
          Ogre::ColourValue color = flatColor ? meshColor : colors[m-1];
          manualObject_->colour(color.r, color.g, color.b, alpha);

          manualObject_->position(vertices[m]);
          manualObject_->normal(normal);
          color = flatColor ? meshColor : colors[m];
          manualObject_->colour(color.r, color.g, color.b, alpha);

          manualObject_->position(vertices[m+1]);
          manualObject_->normal(normal);
          color = flatColor ? meshColor : colors[m+1];
          manualObject_->colour(color.r, color.g, color.b, alpha);
        }

        // plot grid lines
        if (showGridLines) {
          meshLines_->addPoint(vertices[0]);
          meshLines_->addPoint(vertices[1]);
          meshLines_->newLine();

          if (vertices.size() == 3) {
            meshLines_->addPoint(vertices[1]);
            meshLines_->addPoint(vertices[2]);
            meshLines_->newLine();
          } else {
            meshLines_->addPoint(vertices[1]);
            meshLines_->addPoint(vertices[3]);
            meshLines_->newLine();

            meshLines_->addPoint(vertices[3]);
            meshLines_->addPoint(vertices[2]);
            meshLines_->newLine();
          }

          meshLines_->addPoint(vertices[2]);
          meshLines_->addPoint(vertices[0]);
          meshLines_->newLine();
        }
      }
    }
  }

  manualObject_->end();
  material_->getTechnique(0)->setLightingEnabled(false);

  if (alpha < 0.9998) {
    material_->getTechnique(0)->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
    material_->getTechnique(0)->setDepthWriteEnabled(false);
  } else {
    material_->getTechnique(0)->setSceneBlending(Ogre::SBT_REPLACE);
    material_->getTechnique(0)->setDepthWriteEnabled(true);
  }
}

void GridMapVisual::setFramePosition(const Ogre::Vector3& position)
{
  frameNode_->setPosition(position);
}

void GridMapVisual::setFrameOrientation(const Ogre::Quaternion& orientation)
{
  frameNode_->setOrientation(orientation);
}

std::vector<std::string> GridMapVisual::getLayerNames()
{
  return map_.getLayers();
}

// Compute intensity value in the interval [0,1].
void GridMapVisual::normalizeIntensity(float& intensity, float min_intensity, float max_intensity)
{
  intensity = std::min(intensity, max_intensity);
  intensity = std::max(intensity, min_intensity);
  intensity = (intensity - min_intensity) / (max_intensity - min_intensity);
}

// Copied from rviz/src/rviz/default_plugin/point_cloud_transformers.cpp.
Ogre::ColourValue GridMapVisual::getRainbowColor(float intensity)
{
  intensity = std::min(intensity, 1.0f);
  intensity = std::max(intensity, 0.0f);

  float h = intensity * 5.0f + 1.0f;
  int i = floor(h);
  float f = h - i;
  if (!(i & 1)) f = 1 - f;  // if i is even
  float n = 1 - f;

  Ogre::ColourValue color;
  if (i <= 1) color[0] = n, color[1] = 0, color[2] = 1;
  else if (i == 2) color[0] = 0, color[1] = n, color[2] = 1;
  else if (i == 3) color[0] = 0, color[1] = 1, color[2] = n;
  else if (i == 4) color[0] = n, color[1] = 1, color[2] = 0;
  else if (i >= 5) color[0] = 1, color[1] = n, color[2] = 0;

  return color;
}

// Get interpolated color value.
Ogre::ColourValue GridMapVisual::getInterpolatedColor(float intensity, Ogre::ColourValue min_color,
                                                      Ogre::ColourValue max_color)
{
  intensity = std::min(intensity, 1.0f);
  intensity = std::max(intensity, 0.0f);

  Ogre::ColourValue color;
  color.r = intensity * (max_color.r - min_color.r) + min_color.r;
  color.g = intensity * (max_color.g - min_color.g) + min_color.g;
  color.b = intensity * (max_color.b - min_color.b) + min_color.b;

  return color;
}

}  // namespace
<|endoftext|>


<commit_before>#include <jni.h>
#include <string>
#include "Monero.h"

Monero::AndroidWallet  wallet2;

extern "C"
JNIEXPORT jboolean JNICALL
Java_com_example_root_monerotest_Services_SyncWalletService_InitWallet(
        JNIEnv *env,
        jobject /* this */,jstring Path)
{
    bool init =false ;
    string path = env->GetStringUTFChars(Path,0);

   if (std::ifstream(path+"/monero/example.keys")) {

       //159.203.250.205:38081
       //192.168.1.141:28081
        init = wallet2.init("192.168.1.141:28081", "password", path+"/monero/example", true, 4);
   } else
   {
       wallet2.GenerateWallet(path,"example","password");

      init =   wallet2.init("192.168.1.141:28081", "password", path+"/moenro/example", true, 4);
   }

    return init;
}

extern "C"
JNIEXPORT jint JNICALL
Java_com_example_root_monerotest_Services_SyncWalletService_WalletHeight(
        JNIEnv *env,
        jobject /* this */) {

    return wallet2.WalletLocalHeight();

}

extern "C"
JNIEXPORT jint JNICALL
Java_com_example_root_monerotest_Services_SyncWalletService_DaemonHeight(
        JNIEnv *env,
        jobject /* this */) {

    return wallet2.DaemonHeight();

}

extern "C"
JNIEXPORT jint JNICALL
Java_com_example_root_monerotest_MainActivity_WalletHeight(
        JNIEnv *env,
        jobject /* this */) {

    return wallet2.WalletLocalHeight();

}

extern "C"
JNIEXPORT jint JNICALL
Java_com_example_root_monerotest_MainActivity_DaemonHeight(
        JNIEnv *env,
        jobject /* this */) {

    return wallet2.DaemonHeight();

}

extern "C"
JNIEXPORT void JNICALL
Java_com_example_root_monerotest_Services_SyncWalletService_WalletRefresh(
        JNIEnv *env,
        jobject /* this */) {

    wallet2.refresh();

}

extern "C"
JNIEXPORT jboolean JNICALL
Java_com_example_root_monerotest_DashboardFragment_CheckConnection(
        JNIEnv *env,
        jobject /* this */)
{

    return wallet2.Check_Connection();
}

extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_root_monerotest_DashboardFragment_Transfers(
        JNIEnv *env,
        jobject /* this */)
{
    if(wallet2.isnull())
    {
        string ret ="[]";
        return env->NewStringUTF(ret.c_str());
    }

    std::multimap<uint64_t, std::pair<bool,std::string>> transfer  = wallet2.get_transfers();

    int count =0 ;
    string temp = "[";
    jstring str;
    jobjectArray payment;
    jsize len = transfer.size();

    payment = (*env).NewObjectArray(len,env->FindClass("java/lang/String"),0);
    // print in and out sorted by height
    for (std::map<uint64_t, std::pair<bool, std::string>>::const_iterator i = transfer.begin(); i != transfer.end(); ++i) {
        //   message_writer(i->second.first ? console_color_green : console_color_magenta, false) <<
        //                                                                                boost::format("%8.8llu %6.6s %s") %
        //                                                                                ((unsigned long long)i->first) % (i->second.first ? tr("in") : tr("out")) % i->second.second;

        bool in_out = i->second.first;
        string address = i->second.second;
        uint64_t height =  i->first;

        temp += address +",";

        str = env->NewStringUTF(temp.c_str());

        env->SetObjectArrayElement(payment,count,str);
        count++;
    }

    int i = temp.find_last_of(",");
    temp = temp.substr(0,i)+"]";
    return env->NewStringUTF(temp.c_str());
}
extern "C"
JNIEXPORT jdouble JNICALL
Java_com_example_root_monerotest_DashboardFragment_Balance(
        JNIEnv *env,
        jobject /* this */)
{
    return  wallet2.Balance();
}

extern "C"
JNIEXPORT jdouble JNICALL
Java_com_example_root_monerotest_DashboardFragment_UnlockedBalance(
        JNIEnv *env,
        jobject /* this */)
{
    return wallet2.UnlockedBalance();
}

extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_root_monerotest_MenuFragments_SendFragment_SendTransfer(
        JNIEnv *env, jobject /* this */,jstring Address,jdouble Amount) {

    string address = env->GetStringUTFChars(Address,0);

    wallet2.transfer(address,Amount *1000000000000,"",0);

    return env->NewStringUTF(wallet2.pending_tx.c_str());
}
extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_root_monerotest_MainActivity_SendTransfer(
        JNIEnv *env, jobject /* this */,jstring Address,jdouble Amount) {

    string address = env->GetStringUTFChars(Address,0);

    wallet2.transfer(address,Amount *1000000000000,"",0);

    return env->NewStringUTF(wallet2.pending_tx.c_str());
}
extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_root_monerotest_QRGenerator_QRGeneratorFragment_GeneratePaymentId(
        JNIEnv *env, jobject /* this */) {

    return env->NewStringUTF(wallet2.get_payment_id().c_str());
}

extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_root_monerotest_QRGenerator_QRGeneratorFragment_GetAddress(
        JNIEnv *env, jobject /* this */) {

    return env->NewStringUTF(wallet2.address().c_str());
}<commit_msg>null check<commit_after>#include <jni.h>
#include <string>
#include "Monero.h"

Monero::AndroidWallet  wallet2;

extern "C"
JNIEXPORT jboolean JNICALL
Java_com_example_root_monerotest_Services_SyncWalletService_InitWallet(
        JNIEnv *env,
        jobject /* this */,jstring Path)
{
    bool init =false ;
    string path = env->GetStringUTFChars(Path,0);

   if (std::ifstream(path+"/monero/example.keys")) {

       //159.203.250.205:38081
       //192.168.1.141:28081
        init = wallet2.init("192.168.1.141:28081", "password", path+"/monero/example", true, 4);
   } else
   {
       wallet2.GenerateWallet(path,"example","password");

      init =   wallet2.init("192.168.1.141:28081", "password", path+"/moenro/example", true, 4);
   }

    return init;
}

extern "C"
JNIEXPORT jint JNICALL
Java_com_example_root_monerotest_Services_SyncWalletService_WalletHeight(
        JNIEnv *env,
        jobject /* this */) {

    return wallet2.WalletLocalHeight();

}

extern "C"
JNIEXPORT jint JNICALL
Java_com_example_root_monerotest_Services_SyncWalletService_DaemonHeight(
        JNIEnv *env,
        jobject /* this */) {

    return wallet2.DaemonHeight();

}

extern "C"
JNIEXPORT jint JNICALL
Java_com_example_root_monerotest_MainActivity_WalletHeight(
        JNIEnv *env,
        jobject /* this */) {

    return wallet2.WalletLocalHeight();

}

extern "C"
JNIEXPORT jint JNICALL
Java_com_example_root_monerotest_MainActivity_DaemonHeight(
        JNIEnv *env,
        jobject /* this */) {

    return wallet2.DaemonHeight();

}

extern "C"
JNIEXPORT void JNICALL
Java_com_example_root_monerotest_Services_SyncWalletService_WalletRefresh(
        JNIEnv *env,
        jobject /* this */) {

    wallet2.refresh();

}

extern "C"
JNIEXPORT jboolean JNICALL
Java_com_example_root_monerotest_DashboardFragment_CheckConnection(
        JNIEnv *env,
        jobject /* this */)
{

    return wallet2.Check_Connection();
}

extern "C"
JNIEXPORT jboolean JNICALL
Java_com_example_root_monerotest_DashboardFragment_WalletAvailable(
        JNIEnv *env,
        jobject /* this */)
{
    return !wallet2.isnull();
}

extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_root_monerotest_DashboardFragment_Transfers(
        JNIEnv *env,
        jobject /* this */)
{
    if(wallet2.isnull())
    {
        string ret ="[]";
        return env->NewStringUTF(ret.c_str());
    }

    std::multimap<uint64_t, std::pair<bool,std::string>> transfer  = wallet2.get_transfers();

    int count =0 ;
    string temp = "[";
    jstring str;
    jobjectArray payment;
    jsize len = transfer.size();

    payment = (*env).NewObjectArray(len,env->FindClass("java/lang/String"),0);
    // print in and out sorted by height
    for (std::map<uint64_t, std::pair<bool, std::string>>::const_iterator i = transfer.begin(); i != transfer.end(); ++i) {
        //   message_writer(i->second.first ? console_color_green : console_color_magenta, false) <<
        //                                                                                boost::format("%8.8llu %6.6s %s") %
        //                                                                                ((unsigned long long)i->first) % (i->second.first ? tr("in") : tr("out")) % i->second.second;

        bool in_out = i->second.first;
        string address = i->second.second;
        uint64_t height =  i->first;

        temp += address +",";

        str = env->NewStringUTF(temp.c_str());

        env->SetObjectArrayElement(payment,count,str);
        count++;
    }

    int i = temp.find_last_of(",");
    temp = temp.substr(0,i)+"]";
    return env->NewStringUTF(temp.c_str());
}
extern "C"
JNIEXPORT jdouble JNICALL
Java_com_example_root_monerotest_DashboardFragment_Balance(
        JNIEnv *env,
        jobject /* this */)
{
    return  wallet2.Balance();
}

extern "C"
JNIEXPORT jdouble JNICALL
Java_com_example_root_monerotest_DashboardFragment_UnlockedBalance(
        JNIEnv *env,
        jobject /* this */)
{
    return wallet2.UnlockedBalance();
}

extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_root_monerotest_MenuFragments_SendFragment_SendTransfer(
        JNIEnv *env, jobject /* this */,jstring Address,jdouble Amount) {

    string address = env->GetStringUTFChars(Address,0);

    wallet2.transfer(address,Amount *1000000000000,"",0);

    return env->NewStringUTF(wallet2.pending_tx.c_str());
}
extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_root_monerotest_MainActivity_SendTransfer(
        JNIEnv *env, jobject /* this */,jstring Address,jdouble Amount) {

    string address = env->GetStringUTFChars(Address,0);

    wallet2.transfer(address,Amount *1000000000000,"",0);

    return env->NewStringUTF(wallet2.pending_tx.c_str());
}
extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_root_monerotest_QRGenerator_QRGeneratorFragment_GeneratePaymentId(
        JNIEnv *env, jobject /* this */) {

    return env->NewStringUTF(wallet2.get_payment_id().c_str());
}

extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_root_monerotest_QRGenerator_QRGeneratorFragment_GetAddress(
        JNIEnv *env, jobject /* this */) {

    return env->NewStringUTF(wallet2.address().c_str());
}<|endoftext|>


<commit_before>#include "types.h"
#include "amd64.h"
#include "bits.hh"
#include "kernel.hh"
#include "traps.h"
#include "cpu.hh"
#include "apic.hh"
#include "kstream.hh"
#include "bitset.hh"

#define ID      0x802   // ID
#define VER     0x803   // Version
#define TPR     0x808   // Task Priority
#define PPR     0x80a   // Processor Priority
#define EOI     0x80b   // EOI
#define LDR     0x80d   // Logical Destination
#define SVR     0x80f   // Spurious Interrupt Vector
  #define ENABLE     0x00000100   // Unit Enable
  #define NO_BROADCAST (1<<12)    // Disable EOI broadcast
#define ISR     0x810
  #define ISR_NR     0x8
#define TMR     0x818
#define IRR     0x820
#define ESR     0x828ull   // Error Status
#define ICR     0x830ull   // Interrupt Command
  #define INIT       0x00000500ull   // INIT/RESET
  #define STARTUP    0x00000600   // Startup IPI
  #define BCAST      0x00080000   // Send to all APICs, including self.
  #define LEVEL      0x00008000ull   // Level triggered
  #define ASSERT     0x00004000   // Assert interrupt (vs deassert)
  #define DEASSERT   0x00000000
  #define FIXED      0x00000000
#define TIMER   0x832   // Local Vector Table 0 (TIMER)
  #define X1         0x0000000B   // divide counts by 1
  #define PERIODIC   0x00020000   // Periodic
#define THERM   0x833   // Thermal sensor LVT
#define PCINT   0x834   // Performance Counter LVT
#define LINT0   0x835   // Local Vector Table 1 (LINT0)
#define LINT1   0x836   // Local Vector Table 2 (LINT1)
#define ERROR   0x837   // Local Vector Table 3 (ERROR)
  #define MASKED     0x00010000   // Interrupt masked
  #define MT_EXTINT  0x00000500
  #define MT_NMI     0x00000400   // NMI message type
  #define MT_FIX     0x00000000   // Fixed message type
#define TICR    0x838   // Timer Initial Count
#define TCCR    0x839   // Timer Current Count
#define TDCR    0x83e   // Timer Divide Configuration

static console_stream verbose(true);

static u64 x2apichz;

class x2apic_lapic : public abstract_lapic
{
public:
  void cpu_init();
  hwid_t id();
  void eoi();
  void send_ipi(struct cpu *c, int ino);
  void mask_pc(bool mask);
  void start_ap(struct cpu *c, u32 addr);
  bool is_x2apic();
  void dump();
  void dumpall();
private:
  void clearintr();
};

static int
x2apicmaxlvt(void)
{
  unsigned int v;

  v = readmsr(VER);
  return (((v) >> 16) & 0xFFu);
}

void
x2apic_lapic::eoi()
{
  writemsr(EOI, 0);
}

static int
x2apicwait(void)
{
  // Do nothing on x2apic
  return 0;
}

// Code closely follows native_cpu_up, do_boot_cpu,
// and wakeup_secondary_cpu_via_init in Linux v3.3
void
x2apic_lapic::start_ap(struct cpu *c, u32 addr)
{
  int i;

  // Be paranoid about clearing APIC errors
  writemsr(ESR, 0);
  readmsr(ESR);

  unsigned long accept_status;
  int maxlvt = x2apicmaxlvt();

  if (maxlvt > 3)
    writemsr(ESR, 0);
  readmsr(ESR);

  // "Universal startup algorithm."
  // Send INIT (level-triggered) interrupt to reset other CPU.
  // Asserting INIT
  writemsr(ICR, (((u64)c->hwid.num)<<32) | INIT | LEVEL | ASSERT);
  microdelay(10000);
  // Deasserting INIT
  writemsr(ICR, (((u64)c->hwid.num)<<32) | INIT | LEVEL);
  x2apicwait();

  // Send startup IPI (twice!) to enter bootstrap code.
  // Regular hardware is supposed to only accept a STARTUP
  // when it is in the halted state due to an INIT.  So the second
  // should be ignored, but it is part of the official Intel algorithm.
  for(i = 0; i < 2; i++){
    writemsr(ESR, 0);
    readmsr(ESR);

    // Kick the target chip
    writemsr(ICR, (((u64)c->hwid.num)<<32) | STARTUP | (addr>>12));
    // Linux gives 300 usecs to accept the IPI..
    microdelay(300);
    x2apicwait();
    // ..then it gives some more time
    microdelay(200);

    if (maxlvt > 3)
      writemsr(ESR, 0);

    accept_status = (readmsr(ESR) & 0xEF);
    if (accept_status)
      panic("x2apicstartap: accept status %lx", accept_status);
  }
}

void
x2apic_lapic::mask_pc(bool mask)
{
  writemsr(PCINT, mask ? MASKED : MT_NMI);
}

void
x2apic_lapic::send_ipi(struct cpu *c, int ino)
{
  // Unlike other MSR writes, x2apic writes are NOT serializing and
  // hence an IPI may be received before local writes become visible.
  // Prevent this by first performing an mfence.
  asm volatile("mfence");
  writemsr(ICR, (((u64)c->hwid.num)<<32) | FIXED | DEASSERT | ino);
}

hwid_t
x2apic_lapic::id()
{
  u64 id = readmsr(ID);
  return HWID((u32)id);
}

bool
x2apic_lapic::is_x2apic()
{
  return true;
}

void
x2apic_lapic::clearintr()
{
  // Clear any pending interrupts.  Linux does this.
  unsigned int value, queued;
  int i, j, acked = 0;
  unsigned long long tsc = 0, ntsc;
  long long max_loops = 2400000;

  tsc = rdtsc();
  do {
    queued = 0;
    for (i = ISR_NR - 1; i >= 0; i--)
      queued |= readmsr(IRR + i*0x1);

    for (i = ISR_NR - 1; i >= 0; i--) {
      value = readmsr(ISR + i*0x1);
      for (j = 31; j >= 0; j--) {
        if (value & (1<<j)) {
          eoi();
          acked++;
        }
      }
    }
    if (acked > 256) {
      cprintf("x2apic pending interrupts after %d EOI\n",
              acked);
      break;
    }
    ntsc = rdtsc();
    max_loops = (2400000 << 10) - (ntsc - tsc);
  } while (queued && max_loops > 0);
}

// Code closely follows setup_local_APIC in Linux v3.3
void
x2apic_lapic::cpu_init()
{
  u64 count;
  u32 value;
  int maxlvt;

  verbose.println("x2apic: Initializing LAPIC (CPU ", myid(), ")");

  // Enable performance counter overflow interrupts for sampler.cc
  mask_pc(false);

  // Enable interrupts on the APIC (but not on the processor).
  value = readmsr(TPR);
  value &= ~0xffU;
  writemsr(TPR, value);

  clearintr();

  // Enable local APIC and EOI broadcast; set spurious interrupt vector.
  value = readmsr(SVR);
  value &= ~0x000FF;
  value |= ENABLE;
  value &= ~NO_BROADCAST;
  value |= T_IRQ0 + IRQ_SPURIOUS;
  writemsr(SVR, value);

  writemsr(LINT0, MT_EXTINT | MASKED);
  if (readmsr(ID) == 0)
    writemsr(LINT1, MT_NMI);
  else
    writemsr(LINT1, MT_NMI | MASKED);

  maxlvt = x2apicmaxlvt();
  if (maxlvt > 3)
    writemsr(ESR, 0);

  // enables sending errors
  value = T_IRQ0 + IRQ_ERROR;
  writemsr(ERROR, value);

  if (maxlvt > 3)
    writemsr(ESR, 0);
  readmsr(ESR);

  // Send an Init Level De-Assert to synchronise arbitration ID's.
  writemsr(ICR, BCAST | INIT | LEVEL);

  if (x2apichz == 0) {
    // Measure the TICR frequency
    writemsr(TDCR, X1);
    writemsr(TICR, 0xffffffff);
    u64 ccr0 = readmsr(TCCR);
    microdelay(10 * 1000);    // 1/100th of a second
    u64 ccr1 = readmsr(TCCR);
    x2apichz = 100 * (ccr0 - ccr1);
  }

  count = (QUANTUM*x2apichz) / 1000;
  if (count > 0xffffffff)
    panic("initx2apic: QUANTUM too large");

  // The timer repeatedly counts down at bus frequency
  // from xapic[TICR] and then issues an interrupt.
  writemsr(TDCR, X1);
  writemsr(TIMER, PERIODIC | (T_IRQ0 + IRQ_TIMER));
  writemsr(TICR, count);

  // Clear error status register (requires back-to-back writes).
  writemsr(ESR, 0);
  writemsr(ESR, 0);

  // Ack any outstanding interrupts.
  writemsr(EOI, 0);

  return;
}

void
x2apic_lapic::dump()
{
  bitset<256> isr, irr, tmr;
  scoped_cli cli();
  for (int word = 0; word < ISR_NR; ++word) {
    isr.setword(word * 32, readmsr(ISR + word));
    irr.setword(word * 32, readmsr(IRR + word));
    tmr.setword(word * 32, readmsr(TMR + word));
  }
  if (isr.any() || irr.any() || tmr.any())
    // Fixed-mode interrupt vectors that are awaiting EOI (ISR), that
    // are pending delivery (IRR), and are level-triggered and will
    // trigger an IOAPIC EOI when acknowledged (TMR).
    console.println("LAPIC INT  ISR ", isr, " IRR ", irr, " TMR ", tmr);
}

void
x2apic_lapic::dumpall()
{
  scoped_cli cli();
  console.println("LAPIC CPU ", myid());
#define SHOW(reg) console.println("  " #reg "\t", shex(readmsr(reg)).width(10).pad())
  SHOW(ID);
  SHOW(VER);
  SHOW(TPR);
  SHOW(PPR);
  SHOW(LDR);
  SHOW(SVR);
  SHOW(ESR);
  SHOW(ICR);
  SHOW(TIMER);
  SHOW(THERM);
  SHOW(PCINT);
  SHOW(LINT0);
  SHOW(LINT1);
  SHOW(ERROR);
  SHOW(TICR);
  SHOW(TCCR);
  SHOW(TDCR);
#undef SHOW
}

bool
initlapic_x2apic(void)
{
  u32 ecx;
  cpuid(CPUID_FEATURES, nullptr, nullptr, &ecx, nullptr);
  if (!(ecx & FEATURE_ECX_X2APIC))
    return false;

  // According to [Intel SDM 3A 10.12.8.1], if the BIOS initializes
  // logical processors with APIC IDs greater than 255, then it should
  // enable the x2APIC.
  u64 apic_bar = readmsr(MSR_APIC_BAR);
  if (!(apic_bar & APIC_BAR_X2APIC_EN) || !(apic_bar & APIC_BAR_XAPIC_EN))
    return false;

  verbose.println("x2apic: Using x2APIC LAPIC");
  static x2apic_lapic apic;
  lapic = &apic;
  return true;
}
<commit_msg>x2apic: Unmask performance counter LVT after enabling x2APIC<commit_after>#include "types.h"
#include "amd64.h"
#include "bits.hh"
#include "kernel.hh"
#include "traps.h"
#include "cpu.hh"
#include "apic.hh"
#include "kstream.hh"
#include "bitset.hh"

#define ID      0x802   // ID
#define VER     0x803   // Version
#define TPR     0x808   // Task Priority
#define PPR     0x80a   // Processor Priority
#define EOI     0x80b   // EOI
#define LDR     0x80d   // Logical Destination
#define SVR     0x80f   // Spurious Interrupt Vector
  #define ENABLE     0x00000100   // Unit Enable
  #define NO_BROADCAST (1<<12)    // Disable EOI broadcast
#define ISR     0x810
  #define ISR_NR     0x8
#define TMR     0x818
#define IRR     0x820
#define ESR     0x828ull   // Error Status
#define ICR     0x830ull   // Interrupt Command
  #define INIT       0x00000500ull   // INIT/RESET
  #define STARTUP    0x00000600   // Startup IPI
  #define BCAST      0x00080000   // Send to all APICs, including self.
  #define LEVEL      0x00008000ull   // Level triggered
  #define ASSERT     0x00004000   // Assert interrupt (vs deassert)
  #define DEASSERT   0x00000000
  #define FIXED      0x00000000
#define TIMER   0x832   // Local Vector Table 0 (TIMER)
  #define X1         0x0000000B   // divide counts by 1
  #define PERIODIC   0x00020000   // Periodic
#define THERM   0x833   // Thermal sensor LVT
#define PCINT   0x834   // Performance Counter LVT
#define LINT0   0x835   // Local Vector Table 1 (LINT0)
#define LINT1   0x836   // Local Vector Table 2 (LINT1)
#define ERROR   0x837   // Local Vector Table 3 (ERROR)
  #define MASKED     0x00010000   // Interrupt masked
  #define MT_EXTINT  0x00000500
  #define MT_NMI     0x00000400   // NMI message type
  #define MT_FIX     0x00000000   // Fixed message type
#define TICR    0x838   // Timer Initial Count
#define TCCR    0x839   // Timer Current Count
#define TDCR    0x83e   // Timer Divide Configuration

static console_stream verbose(true);

static u64 x2apichz;

class x2apic_lapic : public abstract_lapic
{
public:
  void cpu_init();
  hwid_t id();
  void eoi();
  void send_ipi(struct cpu *c, int ino);
  void mask_pc(bool mask);
  void start_ap(struct cpu *c, u32 addr);
  bool is_x2apic();
  void dump();
  void dumpall();
private:
  void clearintr();
};

static int
x2apicmaxlvt(void)
{
  unsigned int v;

  v = readmsr(VER);
  return (((v) >> 16) & 0xFFu);
}

void
x2apic_lapic::eoi()
{
  writemsr(EOI, 0);
}

static int
x2apicwait(void)
{
  // Do nothing on x2apic
  return 0;
}

// Code closely follows native_cpu_up, do_boot_cpu,
// and wakeup_secondary_cpu_via_init in Linux v3.3
void
x2apic_lapic::start_ap(struct cpu *c, u32 addr)
{
  int i;

  // Be paranoid about clearing APIC errors
  writemsr(ESR, 0);
  readmsr(ESR);

  unsigned long accept_status;
  int maxlvt = x2apicmaxlvt();

  if (maxlvt > 3)
    writemsr(ESR, 0);
  readmsr(ESR);

  // "Universal startup algorithm."
  // Send INIT (level-triggered) interrupt to reset other CPU.
  // Asserting INIT
  writemsr(ICR, (((u64)c->hwid.num)<<32) | INIT | LEVEL | ASSERT);
  microdelay(10000);
  // Deasserting INIT
  writemsr(ICR, (((u64)c->hwid.num)<<32) | INIT | LEVEL);
  x2apicwait();

  // Send startup IPI (twice!) to enter bootstrap code.
  // Regular hardware is supposed to only accept a STARTUP
  // when it is in the halted state due to an INIT.  So the second
  // should be ignored, but it is part of the official Intel algorithm.
  for(i = 0; i < 2; i++){
    writemsr(ESR, 0);
    readmsr(ESR);

    // Kick the target chip
    writemsr(ICR, (((u64)c->hwid.num)<<32) | STARTUP | (addr>>12));
    // Linux gives 300 usecs to accept the IPI..
    microdelay(300);
    x2apicwait();
    // ..then it gives some more time
    microdelay(200);

    if (maxlvt > 3)
      writemsr(ESR, 0);

    accept_status = (readmsr(ESR) & 0xEF);
    if (accept_status)
      panic("x2apicstartap: accept status %lx", accept_status);
  }
}

void
x2apic_lapic::mask_pc(bool mask)
{
  writemsr(PCINT, mask ? MASKED : MT_NMI);
}

void
x2apic_lapic::send_ipi(struct cpu *c, int ino)
{
  // Unlike other MSR writes, x2apic writes are NOT serializing and
  // hence an IPI may be received before local writes become visible.
  // Prevent this by first performing an mfence.
  asm volatile("mfence");
  writemsr(ICR, (((u64)c->hwid.num)<<32) | FIXED | DEASSERT | ino);
}

hwid_t
x2apic_lapic::id()
{
  u64 id = readmsr(ID);
  return HWID((u32)id);
}

bool
x2apic_lapic::is_x2apic()
{
  return true;
}

void
x2apic_lapic::clearintr()
{
  // Clear any pending interrupts.  Linux does this.
  unsigned int value, queued;
  int i, j, acked = 0;
  unsigned long long tsc = 0, ntsc;
  long long max_loops = 2400000;

  tsc = rdtsc();
  do {
    queued = 0;
    for (i = ISR_NR - 1; i >= 0; i--)
      queued |= readmsr(IRR + i*0x1);

    for (i = ISR_NR - 1; i >= 0; i--) {
      value = readmsr(ISR + i*0x1);
      for (j = 31; j >= 0; j--) {
        if (value & (1<<j)) {
          eoi();
          acked++;
        }
      }
    }
    if (acked > 256) {
      cprintf("x2apic pending interrupts after %d EOI\n",
              acked);
      break;
    }
    ntsc = rdtsc();
    max_loops = (2400000 << 10) - (ntsc - tsc);
  } while (queued && max_loops > 0);
}

// Code closely follows setup_local_APIC in Linux v3.3
void
x2apic_lapic::cpu_init()
{
  u64 count;
  u32 value;
  int maxlvt;

  verbose.println("x2apic: Initializing LAPIC (CPU ", myid(), ")");

  // Enable interrupts on the APIC (but not on the processor).
  value = readmsr(TPR);
  value &= ~0xffU;
  writemsr(TPR, value);

  clearintr();

  // Enable local APIC and EOI broadcast; set spurious interrupt vector.
  value = readmsr(SVR);
  value &= ~0x000FF;
  value |= ENABLE;
  value &= ~NO_BROADCAST;
  value |= T_IRQ0 + IRQ_SPURIOUS;
  writemsr(SVR, value);

  writemsr(LINT0, MT_EXTINT | MASKED);
  if (readmsr(ID) == 0)
    writemsr(LINT1, MT_NMI);
  else
    writemsr(LINT1, MT_NMI | MASKED);

  maxlvt = x2apicmaxlvt();
  if (maxlvt > 3)
    writemsr(ESR, 0);

  // enables sending errors
  value = T_IRQ0 + IRQ_ERROR;
  writemsr(ERROR, value);

  // Enable performance counter overflow interrupts for sampler.cc
  mask_pc(false);

  if (maxlvt > 3)
    writemsr(ESR, 0);
  readmsr(ESR);

  // Send an Init Level De-Assert to synchronise arbitration ID's.
  writemsr(ICR, BCAST | INIT | LEVEL);

  if (x2apichz == 0) {
    // Measure the TICR frequency
    writemsr(TDCR, X1);
    writemsr(TICR, 0xffffffff);
    u64 ccr0 = readmsr(TCCR);
    microdelay(10 * 1000);    // 1/100th of a second
    u64 ccr1 = readmsr(TCCR);
    x2apichz = 100 * (ccr0 - ccr1);
  }

  count = (QUANTUM*x2apichz) / 1000;
  if (count > 0xffffffff)
    panic("initx2apic: QUANTUM too large");

  // The timer repeatedly counts down at bus frequency
  // from xapic[TICR] and then issues an interrupt.
  writemsr(TDCR, X1);
  writemsr(TIMER, PERIODIC | (T_IRQ0 + IRQ_TIMER));
  writemsr(TICR, count);

  // Clear error status register (requires back-to-back writes).
  writemsr(ESR, 0);
  writemsr(ESR, 0);

  // Ack any outstanding interrupts.
  writemsr(EOI, 0);

  return;
}

void
x2apic_lapic::dump()
{
  bitset<256> isr, irr, tmr;
  scoped_cli cli();
  for (int word = 0; word < ISR_NR; ++word) {
    isr.setword(word * 32, readmsr(ISR + word));
    irr.setword(word * 32, readmsr(IRR + word));
    tmr.setword(word * 32, readmsr(TMR + word));
  }
  if (isr.any() || irr.any() || tmr.any())
    // Fixed-mode interrupt vectors that are awaiting EOI (ISR), that
    // are pending delivery (IRR), and are level-triggered and will
    // trigger an IOAPIC EOI when acknowledged (TMR).
    console.println("LAPIC INT  ISR ", isr, " IRR ", irr, " TMR ", tmr);
}

void
x2apic_lapic::dumpall()
{
  scoped_cli cli();
  console.println("LAPIC CPU ", myid());
#define SHOW(reg) console.println("  " #reg "\t", shex(readmsr(reg)).width(10).pad())
  SHOW(ID);
  SHOW(VER);
  SHOW(TPR);
  SHOW(PPR);
  SHOW(LDR);
  SHOW(SVR);
  SHOW(ESR);
  SHOW(ICR);
  SHOW(TIMER);
  SHOW(THERM);
  SHOW(PCINT);
  SHOW(LINT0);
  SHOW(LINT1);
  SHOW(ERROR);
  SHOW(TICR);
  SHOW(TCCR);
  SHOW(TDCR);
#undef SHOW
}

bool
initlapic_x2apic(void)
{
  u32 ecx;
  cpuid(CPUID_FEATURES, nullptr, nullptr, &ecx, nullptr);
  if (!(ecx & FEATURE_ECX_X2APIC))
    return false;

  // According to [Intel SDM 3A 10.12.8.1], if the BIOS initializes
  // logical processors with APIC IDs greater than 255, then it should
  // enable the x2APIC.
  u64 apic_bar = readmsr(MSR_APIC_BAR);
  if (!(apic_bar & APIC_BAR_X2APIC_EN) || !(apic_bar & APIC_BAR_XAPIC_EN))
    return false;

  verbose.println("x2apic: Using x2APIC LAPIC");
  static x2apic_lapic apic;
  lapic = &apic;
  return true;
}
<|endoftext|>