<commit_before>#include "option_manager.hh"

#include <sstream>

namespace Kakoune
{

Option& OptionManager::operator[] (const String& name)
{
    auto it = m_options.find(name);
    if (it != m_options.end())
        return it->second;
    else if (m_parent)
        return (*m_parent)[name];
    else
        return m_options[name];
}

const Option& OptionManager::operator[] (const String& name) const
{
    auto it = m_options.find(name);
    if (it != m_options.end())
        return it->second;
    else if (m_parent)
        return (*m_parent)[name];
    else
        throw option_not_found(name);
}

CandidateList OptionManager::complete_option_name(const String& prefix,
                                                  size_t cursor_pos)
{
    String real_prefix = prefix.substr(0, cursor_pos);
    CandidateList result;
    if (m_parent)
        result = m_parent->complete_option_name(prefix, cursor_pos);
    for (auto& option : m_options)
    {
        if (option.first.substr(0, real_prefix.length()) == real_prefix and
            not contains(result, option.first))
            result.push_back(option.first);
    }
    return result;
}

GlobalOptionManager::GlobalOptionManager()
    : OptionManager()
{
    (*this)["tabstop"] = 8;
}

}
<commit_msg>When creating an Option, OptionManager takes it's initial value from it's parent if possible<commit_after>#include "option_manager.hh"

#include <sstream>

namespace Kakoune
{

Option& OptionManager::operator[] (const String& name)
{
    auto it = m_options.find(name);
    if (it != m_options.end())
        return it->second;
    else
    {
        Option& res = m_options[name];
        OptionManager* parent = m_parent;
        while (parent)
        {
            auto parent_it = parent->m_options.find(name);
            if (parent_it != parent->m_options.end())
            {
                res = parent_it->second;
                break;
            }
            else
               parent = parent->m_parent;
        }
        return res;
    }
}

const Option& OptionManager::operator[] (const String& name) const
{
    auto it = m_options.find(name);
    if (it != m_options.end())
        return it->second;
    else if (m_parent)
        return (*m_parent)[name];
    else
        throw option_not_found(name);
}

CandidateList OptionManager::complete_option_name(const String& prefix,
                                                  size_t cursor_pos)
{
    String real_prefix = prefix.substr(0, cursor_pos);
    CandidateList result;
    if (m_parent)
        result = m_parent->complete_option_name(prefix, cursor_pos);
    for (auto& option : m_options)
    {
        if (option.first.substr(0, real_prefix.length()) == real_prefix and
            not contains(result, option.first))
            result.push_back(option.first);
    }
    return result;
}

GlobalOptionManager::GlobalOptionManager()
    : OptionManager()
{
    (*this)["tabstop"] = 8;
}

}
<|endoftext|>


<commit_before>#include <fstream>
#include <boost/timer.hpp>

#include "acrbslam/config.h"
#include "acrbslam/visual_odometry.h"
#include "acrbslam/cloudmap.h"
#include "acrbslam/wifi.h"

namespace acrbslam
{

void *wifi_recv(void *arg)
{
	//struct sockaddr_in Local_Addr;
	//struct sockaddr_in Remote_Addr;
	//int pc_sock,a;
	//socklen_t addr_len=sizeof(Remote_Addr);

	wifi_comu wifi_comu_;
    	wifi_comu_.wifi_init_pc();

	char red[307200];
	char green[307200];
	char blue[307200];
	char depth[76800];
	//char move[48];
	int a;

	Mat picture=Mat::zeros(480,640,CV_8UC3);

	while(1)
	{

		//a=wifi_comu_.receive_data((char*)red,sizeof(red));
		//a=wifi_comu_.receive_data((char*)green,sizeof(green));
		//a=wifi_comu_.receive_data((char*)blue,sizeof(blue));
		//a=wifi_comu_.receive_data(&depth,sizeof(depth));
		//a=wifi_comu_.receive_data(&transform,sizeof(transform));

		//depth_point = (unsigned short int *)(&depth);

		//wifi_comu_.rgbchar2rgbmat(wifi_comu_, picture, red, green, blue);

		wifi_comu_.receive_data_pc(picture);
		imshow("WIFI picture",picture);
		waitKey(0);

/*
		double movement[6];
		double *real_move=(double *)(move);
		movement[0]=*real_move;
		movement[1]=*(++real_move);
		movement[2]=*(++real_move);
		movement[3]=*(++real_move);
		movement[4]=*(++real_move);
		movement[5]=*(++real_move);
		printf("x:%f, y:%f, z:%f, roll:%F, pitch:%F, yaw:%f",movement[0],movement[1],movement[2],movement[3],movement[4],movement[5]);

		printf("OK3\n");

		Mat rvec=Mat::zeros(3,1,CV_64F);
		rvec.at<double>(0,0)=-(double)(movement[3]*3.1415/180.0);
		rvec.at<double>(1,0)=(double)(movement[4]*3.1415/180.0);
		rvec.at<double>(2,0)=-(double)(movement[5]*3.1415/180.0);
		Mat R;
		Rodrigues(rvec,R);
		Eigen::Matrix3d r;

		r(0,0)=R.at<double>(0,0);
		r(0,1)=R.at<double>(0,1);
		r(0,2)=R.at<double>(0,2);
		r(1,0)=R.at<double>(1,0);
		r(1,1)=R.at<double>(1,1);
		r(1,2)=R.at<double>(1,2);
		r(2,0)=R.at<double>(2,0);
		r(2,1)=R.at<double>(2,1);
		r(2,2)=R.at<double>(2,2);

		Eigen::Isometry3d T = Eigen::Isometry3d::Identity();
		Eigen::Isometry3d T1 = Eigen::Isometry3d::Identity();

		Eigen::AngleAxisd angle(r);
		T = angle;

		T(0,3) =-(double)(movement[0]/1000.0);
		T(1,3) =-(double)(movement[1]/1000.0);
		T(2,3) =-(double)(movement[2]/1000.0);

		cout<<"T:"<<T.matrix()<<endl;

		T1=T.inverse();

		pcl::transformPointCloud(*cloud_cur_point,*cloud_cur_trans, T.matrix());
		printf("OK5\n");
		*output += *cloud_cur_trans;

		printf("OK4\n");
	*/
	}
}

/*
void* pcl_3d(void *arg)
{
	pcl::visualization::PCLVisualizer viewer("picture");
	viewer.addPointCloud(output,"one");
	while(1)
	{
//	viewer.addPointCloud(output,"one");
//	viewer.removePointCloud("one");
	viewer.updatePointCloud(output,"one");
	viewer.spinOnce(1300);
	}
}
*/

}	//namespace acrbslam

int main(int argc, char** argv)
{
   	 if ( argc != 2 )
   	 {
       	 cout<<"usage: run_vo parameter_file"<<endl;
      	  return 1;
   	 }
    	acrbslam::Config::setParameterFile ( argv[1] );

	pthread_t thread_wifi_recv;
	void *retval_wifi_recv;
	//pthread_t thread_pcl;
	//void *retval_pcl;

	int ret_wifi=pthread_create(&thread_wifi_recv,NULL,acrbslam::wifi_recv,NULL);
	//int ret_pcl =pthread_create(&thread_pcl,NULL,pcl_3d,NULL);

	while(1);

	pthread_join(thread_wifi_recv,&retval_wifi_recv);
	//pthread_join(thread_pcl,&retval_pcl);

	return 0;

}

<commit_msg>接收程序可以成功接受灰度图mat<commit_after>#include <fstream>
#include <boost/timer.hpp>

#include "acrbslam/config.h"
#include "acrbslam/visual_odometry.h"
#include "acrbslam/cloudmap.h"
#include "acrbslam/wifi.h"

namespace acrbslam
{

void *wifi_recv(void *arg)
{
	wifi_comu wifi_comu_;
    	wifi_comu_.wifi_init_pc();

	Mat picture=Mat::zeros(480,640,CV_8UC3);

	while(1)
	{

		picture=wifi_comu_.receive_data_pc();
		imshow("WIFI picture",picture);
		waitKey(1);

	}
}

}	//namespace acrbslam

int main(int argc, char** argv)
{
   	 if ( argc != 2 )
   	 {
       	 cout<<"usage: run_vo parameter_file"<<endl;
      	  return 1;
   	 }
    	acrbslam::Config::setParameterFile ( argv[1] );

	pthread_t thread_wifi_recv;
	void *retval_wifi_recv;
	//pthread_t thread_pcl;
	//void *retval_pcl;

	int ret_wifi=pthread_create(&thread_wifi_recv,NULL,acrbslam::wifi_recv,NULL);
	//int ret_pcl =pthread_create(&thread_pcl,NULL,pcl_3d,NULL);

	while(1);

	pthread_join(thread_wifi_recv,&retval_wifi_recv);
	//pthread_join(thread_pcl,&retval_pcl);

	return 0;

}

<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

/// \ingroup macros
/// \file MUONRefit.C
/// \brief Macro for refitting ESD tracks from ESD pads
///
/// \author Philippe Pillot, SUBATECH

#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TStopwatch.h>
#include <TFile.h>
#include <TTree.h>
#include <TString.h>
#include <Riostream.h>
#include <TGeoManager.h>
#include <TRandom.h>
#include <TROOT.h>

// STEER includes
#include "AliMagFMaps.h"
#include "AliTracker.h"
#include "AliESDEvent.h"
#include "AliESDMuonTrack.h"
#include "AliRecoParam.h"
#include "AliCDBManager.h"
#include "AliGeomManager.h"

// MUON includes
#include "AliMpCDB.h"
#include "AliMUONRecoParam.h"
#include "AliMUONESDInterface.h"
#include "AliMUONRefitter.h"
#include "AliMUONVDigit.h"
#include "AliMUONVCluster.h"
#include "AliMUONVClusterStore.h"
#include "AliMUONTrack.h"
#include "AliMUONVTrackStore.h"
#include "AliMUONTrackParam.h"
#include "AliMUONTrackExtrap.h"
#endif

const Int_t printLevel = 1;

void Prepare();
TTree* GetESDTree(TFile *esdFile);

//-----------------------------------------------------------------------
void MUONRefit(Int_t nevents = -1, const char* esdFileNameIn = "AliESDs.root", const char* esdFileNameOut = "AliESDs_New.root")
{
  /// refit ESD tracks from ESD pads (i.e. re-clusterized the attached ESD clusters);
  /// reset the charge of the digit using their raw charge before refitting;
  /// compare results with original ESD tracks;
  /// write results in a new ESD file

  // prepare the refitting
  gRandom->SetSeed(1);
  Prepare();

  // set reconstruction parameters used for refitting
  AliMUONRecoParam *muonRecoParam = AliMUONRecoParam::GetLowFluxParam();
  muonRecoParam->Print("FULL");

  AliMUONESDInterface esdInterface;
  AliMUONRefitter refitter(muonRecoParam);
  refitter.Connect(&esdInterface);

  // open the ESD file and tree
  TFile* esdFile = TFile::Open(esdFileNameIn);
  TTree* esdTree = GetESDTree(esdFile);

  // create the ESD output file and tree
  TFile* newESDFile = TFile::Open(esdFileNameOut, "RECREATE");
  newESDFile->SetCompressionLevel(2);
  TTree* newESDTree = esdTree->CloneTree(0);

  // connect ESD event to the ESD tree
  AliESDEvent* esd = new AliESDEvent();
  esd->ReadFromTree(esdTree);

  // timer start...
  TStopwatch timer;

  // Loop over ESD events
  if (nevents > 0) nevents = TMath::Min(nevents,(Int_t)esdTree->GetEntries());
  else nevents = (Int_t)esdTree->GetEntries();
  for (Int_t iEvent = 0; iEvent < nevents; iEvent++) {
    if (printLevel>0) cout<<endl<<"            ****************event #"<<iEvent+1<<"****************"<<endl;

    //----------------------------------------------//
    // -------------- process event --------------- //
    //----------------------------------------------//
    // get the ESD of current event
    esdTree->GetEvent(iEvent);
    if (!esd) {
      Error("CheckESD", "no ESD object found for event %d", iEvent);
      return;
    }
    Int_t nTracks = (Int_t)esd->GetNumberOfMuonTracks();
    if (nTracks < 1) continue;

    // load the current event
    esdInterface.LoadEvent(*esd);

    // loop over digit to modify their charge
    AliMUONVDigit *digit;
    TIter next(esdInterface.CreateDigitIterator());
    while ((digit = static_cast<AliMUONVDigit*>(next()))) {
      digit->SetCharge(digit->ADC());
      digit->Calibrated(kFALSE);
    }

    // refit the tracks from digits
    AliMUONVTrackStore* newTrackStore = refitter.ReconstructFromDigits();

    //----------------------------------------------//
    // ------ fill new ESD and print results ------ //
    //----------------------------------------------//
    // loop over the list of ESD tracks
    TClonesArray *esdTracks = (TClonesArray*) esd->FindListObject("MuonTracks");
    for (Int_t iTrack = 0; iTrack <  nTracks; iTrack++) {

      // get the ESD track
      AliESDMuonTrack* esdTrack = (AliESDMuonTrack*) esdTracks->UncheckedAt(iTrack);

      // skip ghost tracks (leave them unchanged in the new ESD file)
      if (!esdTrack->ContainTrackerData()) continue;

      // get the corresponding MUON track
      AliMUONTrack* track = esdInterface.FindTrack(esdTrack->GetUniqueID());

      // Find the corresponding re-fitted MUON track
      AliMUONTrack* newTrack = (AliMUONTrack*) newTrackStore->FindObject(esdTrack->GetUniqueID());

      // replace the content of the current ESD track or remove it if the refitting has failed
      if (newTrack) {
	Double_t vertex[3] = {esdTrack->GetNonBendingCoor(), esdTrack->GetBendingCoor(), esdTrack->GetZ()};
	AliMUONESDInterface::MUONToESD(*newTrack, *esdTrack, vertex, esdInterface.GetDigits());
      } else {
	esdTracks->Remove(esdTrack);
      }

      // print initial and re-fitted track parameters at first cluster if any
      if (printLevel>0) {
	cout<<"            ----------------track #"<<iTrack+1<<"----------------"<<endl;
	cout<<"before refit:"<<endl;
	AliMUONTrackParam *param = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->First();
	param->Print("FULL");
	if (printLevel>1) param->GetCovariances().Print();
	if (!newTrack) continue;
	cout<<"after refit:"<<endl;
	param = (AliMUONTrackParam*) newTrack->GetTrackParamAtCluster()->First();
	param->Print("FULL");
	if (printLevel>1) param->GetCovariances().Print();
	cout<<"            ----------------------------------------"<<endl;
      }

    }

    // free memory
    delete newTrackStore;

    // fill new ESD tree with new tracks
    esdTracks->Compress();
    newESDTree->Fill();

    if (printLevel>0) cout<<"            ****************************************"<<endl;
  }

  // ...timer stop
  timer.Stop();

  // write output ESD tree
  newESDFile->cd();
  newESDTree->Write();
  delete newESDTree;
  newESDFile->Close();

  // free memory
  esdFile->Close();
  delete esd;

  cout<<endl<<"time to refit: R:"<<timer.RealTime()<<" C:"<<timer.CpuTime()<<endl<<endl;
}

//-----------------------------------------------------------------------
void Prepare()
{
  /// Set the geometry, the magnetic field, the mapping and the reconstruction parameters

  // Import TGeo geometry (needed by AliMUONTrackExtrap::ExtrapToVertex)
  if (!gGeoManager) {
    AliGeomManager::LoadGeometry("geometry.root");
    if (!gGeoManager) {
      Error("MUONRefit", "getting geometry from file %s failed", "generated/galice.root");
      return;
    }
  }

  // set mag field
  printf("Loading field map...\n");
  AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 1, 1., 10., AliMagFMaps::k5kG);
  AliTracker::SetFieldMap(field, kFALSE);
  AliMUONTrackExtrap::SetField(AliTracker::GetFieldMap());

  // Load mapping
  AliCDBManager* man = AliCDBManager::Instance();
  man->SetDefaultStorage("local://$ALICE_ROOT");
  man->SetRun(0);
  if ( ! AliMpCDB::LoadDDLStore() ) {
    Error("MUONRefit","Could not access mapping from OCDB !");
    exit(-1);
  }

}

//-----------------------------------------------------------------------
TTree* GetESDTree(TFile *esdFile)
{
  /// Check that the file is properly open
  /// Return pointer to the ESD Tree

  if (!esdFile || !esdFile->IsOpen()) {
    Error("GetESDTree", "opening ESD file failed");
    exit(-1);
  }

  TTree* tree = (TTree*) esdFile->Get("esdTree");
  if (!tree) {
    Error("GetESDTree", "no ESD tree found");
    exit(-1);
  }

  return tree;

}

<commit_msg>Get initial reconstruction parameters from OCDB (Philippe P.)<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

/// \ingroup macros
/// \file MUONRefit.C
/// \brief Macro for refitting ESD tracks from ESD pads
///
/// \author Philippe Pillot, SUBATECH

#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TStopwatch.h>
#include <TFile.h>
#include <TTree.h>
#include <TString.h>
#include <Riostream.h>
#include <TGeoManager.h>
#include <TRandom.h>
#include <TROOT.h>

// STEER includes
#include "AliMagFMaps.h"
#include "AliTracker.h"
#include "AliESDEvent.h"
#include "AliESDMuonTrack.h"
#include "AliRecoParam.h"
#include "AliCDBManager.h"
#include "AliCDBEntry.h"
#include "AliCDBPath.h"
#include "AliGeomManager.h"

// MUON includes
#include "AliMpCDB.h"
#include "AliMUONRecoParam.h"
#include "AliMUONESDInterface.h"
#include "AliMUONRefitter.h"
#include "AliMUONVDigit.h"
#include "AliMUONTrack.h"
#include "AliMUONVTrackStore.h"
#include "AliMUONTrackParam.h"
#include "AliMUONTrackExtrap.h"
#endif

const Int_t printLevel = 1;

void Prepare();
TTree* GetESDTree(TFile *esdFile);

//-----------------------------------------------------------------------
void MUONRefit(Int_t nevents = -1, const char* esdFileNameIn = "AliESDs.root", const char* esdFileNameOut = "AliESDs_New.root")
{
  /// refit ESD tracks from ESD pads (i.e. re-clusterized the attached ESD clusters);
  /// reset the charge of the digit using their raw charge before refitting;
  /// compare results with original ESD tracks;
  /// write results in a new ESD file

  // prepare the refitting
  gRandom->SetSeed(1);
  Prepare();

  // reconstruction parameters for the refitting
  AliMUONRecoParam* recoParam = AliMUONRecoParam::GetLowFluxParam();
  Info("MUONRefit", "\n Reconstruction parameters for refitting:");
  recoParam->Print("FULL");

  AliMUONESDInterface esdInterface;
  AliMUONRefitter refitter(recoParam);
  refitter.Connect(&esdInterface);

  // open the ESD file and tree
  TFile* esdFile = TFile::Open(esdFileNameIn);
  TTree* esdTree = GetESDTree(esdFile);

  // create the ESD output file and tree
  TFile* newESDFile = TFile::Open(esdFileNameOut, "RECREATE");
  newESDFile->SetCompressionLevel(2);
  TTree* newESDTree = esdTree->CloneTree(0);

  // connect ESD event to the ESD tree
  AliESDEvent* esd = new AliESDEvent();
  esd->ReadFromTree(esdTree);

  // timer start...
  TStopwatch timer;

  // Loop over ESD events
  if (nevents > 0) nevents = TMath::Min(nevents,(Int_t)esdTree->GetEntries());
  else nevents = (Int_t)esdTree->GetEntries();
  for (Int_t iEvent = 0; iEvent < nevents; iEvent++) {
    if (printLevel>0) cout<<endl<<"            ****************event #"<<iEvent+1<<"****************"<<endl;

    //----------------------------------------------//
    // -------------- process event --------------- //
    //----------------------------------------------//
    // get the ESD of current event
    esdTree->GetEvent(iEvent);
    if (!esd) {
      Error("MUONRefit", "no ESD object found for event %d", iEvent);
      return;
    }
    Int_t nTracks = (Int_t)esd->GetNumberOfMuonTracks();
    if (nTracks < 1) continue;

    // load the current event
    esdInterface.LoadEvent(*esd);

    // loop over digit to modify their charge
    AliMUONVDigit *digit;
    TIter next(esdInterface.CreateDigitIterator());
    while ((digit = static_cast<AliMUONVDigit*>(next()))) {
      digit->SetCharge(digit->ADC());
      digit->Calibrated(kFALSE);
    }

    // refit the tracks from digits
    AliMUONVTrackStore* newTrackStore = refitter.ReconstructFromDigits();

    //----------------------------------------------//
    // ------ fill new ESD and print results ------ //
    //----------------------------------------------//
    // loop over the list of ESD tracks
    TClonesArray *esdTracks = (TClonesArray*) esd->FindListObject("MuonTracks");
    for (Int_t iTrack = 0; iTrack <  nTracks; iTrack++) {

      // get the ESD track
      AliESDMuonTrack* esdTrack = (AliESDMuonTrack*) esdTracks->UncheckedAt(iTrack);

      // skip ghost tracks (leave them unchanged in the new ESD file)
      if (!esdTrack->ContainTrackerData()) continue;

      // get the corresponding MUON track
      AliMUONTrack* track = esdInterface.FindTrack(esdTrack->GetUniqueID());

      // Find the corresponding re-fitted MUON track
      AliMUONTrack* newTrack = (AliMUONTrack*) newTrackStore->FindObject(esdTrack->GetUniqueID());

      // replace the content of the current ESD track or remove it if the refitting has failed
      if (newTrack) {
	Double_t vertex[3] = {esdTrack->GetNonBendingCoor(), esdTrack->GetBendingCoor(), esdTrack->GetZ()};
	AliMUONESDInterface::MUONToESD(*newTrack, *esdTrack, vertex, esdInterface.GetDigits());
      } else {
	esdTracks->Remove(esdTrack);
      }

      // print initial and re-fitted track parameters at first cluster if any
      if (printLevel>0) {
	cout<<"            ----------------track #"<<iTrack+1<<"----------------"<<endl;
	cout<<"before refit:"<<endl;
	AliMUONTrackParam *param = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->First();
	param->Print("FULL");
	if (printLevel>1) param->GetCovariances().Print();
	if (!newTrack) continue;
	cout<<"after refit:"<<endl;
	param = (AliMUONTrackParam*) newTrack->GetTrackParamAtCluster()->First();
	param->Print("FULL");
	if (printLevel>1) param->GetCovariances().Print();
	cout<<"            ----------------------------------------"<<endl;
      }

    }

    // free memory
    delete newTrackStore;

    // fill new ESD tree with new tracks
    esdTracks->Compress();
    newESDTree->Fill();

    if (printLevel>0) cout<<"            ****************************************"<<endl;
  }

  // ...timer stop
  timer.Stop();

  // write output ESD tree
  newESDFile->cd();
  newESDTree->Write();
  delete newESDTree;
  newESDFile->Close();

  // free memory
  esdFile->Close();
  delete esd;

  cout<<endl<<"time to refit: R:"<<timer.RealTime()<<" C:"<<timer.CpuTime()<<endl<<endl;
}

//-----------------------------------------------------------------------
void Prepare()
{
  /// Set the geometry, the magnetic field, the mapping and the reconstruction parameters

  // Import TGeo geometry (needed by AliMUONTrackExtrap::ExtrapToVertex)
  if (!gGeoManager) {
    AliGeomManager::LoadGeometry("geometry.root");
    if (!gGeoManager) {
      Error("MUONRefit", "getting geometry from file %s failed", "generated/galice.root");
      return;
    }
  }

  // set mag field
  printf("Loading field map...\n");
  AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 1, 1., 10., AliMagFMaps::k5kG);
  AliTracker::SetFieldMap(field, kFALSE);
  AliMUONTrackExtrap::SetField(AliTracker::GetFieldMap());

  // Load mapping
  AliCDBManager* man = AliCDBManager::Instance();
  man->SetDefaultStorage("local://$ALICE_ROOT");
  man->SetRun(0);
  if ( ! AliMpCDB::LoadDDLStore() ) {
    Error("MUONRefit","Could not access mapping from OCDB !");
    exit(-1);
  }

  // Load initial reconstruction parameters from OCDB
  AliMUONRecoParam* recoParam = 0x0;
  AliCDBPath path("MUON","Calib","RecoParam");
  AliCDBEntry *entry=man->Get(path.GetPath());
  if(entry) {
    recoParam = dynamic_cast<AliMUONRecoParam*>(entry->GetObject());
    entry->SetOwner(0);
    AliCDBManager::Instance()->UnloadFromCache(path.GetPath());
  }
  if (!recoParam) {
    printf("Couldn't find RecoParam object in OCDB: create default one");
    recoParam = AliMUONRecoParam::GetLowFluxParam();
  }
  Info("MUONRefit", "\n initial recontruction parameters:");
  recoParam->Print("FULL");
  AliMUONESDInterface::ResetTracker(recoParam);

}

//-----------------------------------------------------------------------
TTree* GetESDTree(TFile *esdFile)
{
  /// Check that the file is properly open
  /// Return pointer to the ESD Tree

  if (!esdFile || !esdFile->IsOpen()) {
    Error("GetESDTree", "opening ESD file failed");
    exit(-1);
  }

  TTree* tree = (TTree*) esdFile->Get("esdTree");
  if (!tree) {
    Error("GetESDTree", "no ESD tree found");
    exit(-1);
  }

  return tree;

}

<|endoftext|>


<commit_before>#include "system_impl.h"

SystemImpl::SystemImpl(const qbSystemAttr_& attr, qbSystem system) :
  system_(system), join_(attr.join), user_state_(attr.state),
  transform_(attr.transform),
  callback_(attr.callback) {
  for(auto* component : attr.sinks) {
    sinks_.push_back(component->impl);
    sink_interfaces_.push_back(component->impl->interface);
  }
  for(auto* component : attr.sources) {
    sources_.push_back(component->impl);
    source_interfaces_.push_back(component->impl->interface);
  }

  for(auto* source : sources_) {
    qbElement_ element;
    element.read_buffer = nullptr;
    element.user_buffer = nullptr;
    element.size = source->values.size;
    element.indexed_by = qbIndexedBy::QB_INDEXEDBY_KEY;

    elements_.push_back(element);
  }

  for (size_t i = 0; i < sources_.size(); ++i) {
    auto source = sources_[i];
    auto found = std::find(sinks_.begin(), sinks_.end(), source);
    if (found != sinks_.end()) {
      elements_[i].interface = (*found)->interface;
    }
    elements_data_.push_back(&elements_[i]);
  }
}

SystemImpl* SystemImpl::FromRaw(qbSystem system) {
  return (SystemImpl*)(((char*)system) + sizeof(qbSystem_));
}

void SystemImpl::Run(void* event) {
  size_t source_size = sources_.size();
  size_t sink_size = sinks_.size();
  qbFrame frame;
  frame.event = event;
  frame.state = system_->user_state;

  if (transform_) {
    if (source_size == 0 && sink_size == 0) {
      Run_0_To_0(&frame);
    } else if (source_size == 1 && sink_size == 0) {
      Run_1_To_0(&frame);
    } else if (source_size == 1 && sink_size > 0) {
      Run_1_To_N(&frame);
    } else if (source_size == 0 && sink_size > 0) {
      Run_0_To_N(&frame);
    } else if (source_size > 1) {
      Run_M_To_N(&frame);
    }
  }

  if (callback_) {
    callback_(sink_interfaces_.data(), &frame);
  }
}

void SystemImpl::CopyToElement(void* k, void* v, qbOffset offset,
                                 qbElement element) {
  element->id = *(qbId*)k;
  element->read_buffer = v;
  element->offset = offset;
  element->indexed_by = qbIndexedBy::QB_INDEXEDBY_OFFSET;
}

void SystemImpl::CopyToElement(void* k, void* v, qbElement element) {
  element->id = *(qbId*)k;
  element->read_buffer = v;
  element->indexed_by = qbIndexedBy::QB_INDEXEDBY_KEY;
}

void SystemImpl::Run_0_To_0(qbFrame* f) {
  transform_(nullptr, nullptr, f);
}

void SystemImpl::Run_1_To_0(qbFrame* f) {
  qbCollection source = sources_[0];
  uint64_t count = source->count(&source->interface);
  uint8_t* keys = source->keys.data(&source->interface);
  uint8_t* values = source->values.data(&source->interface);

  for(uint64_t i = 0; i < count; ++i) {
    CopyToElement(
        (void*)(keys + source->keys.offset + i * source->keys.stride),
        (void*)(values + source->values.offset + i * source->values.stride),
        i, &elements_.front());
    transform_(elements_data_.data(), nullptr, f);
  }
}

void SystemImpl::Run_0_To_N(qbFrame* f) {
  transform_(nullptr, sink_interfaces_.data(), f);
}

void SystemImpl::Run_1_To_N(qbFrame* f) {
  qbCollection source = sources_[0];
  const uint64_t count = source->count(&source->interface);
  const uint8_t* keys = source->keys.data(&source->interface);
  const uint8_t* values = source->values.data(&source->interface);
  for(uint64_t i = 0; i < count; ++i) {
    CopyToElement(
        (void*)(keys + source->keys.offset + i * source->keys.stride),
        (void*)(values + source->values.offset + i * source->values.stride),
        i, &elements_.front());
    transform_(elements_data_.data(), sink_interfaces_.data(), f);
  }
}

void SystemImpl::Run_M_To_N(qbFrame* f) {
  qbCollection source = sources_[0];
  switch(join_) {
    case qbComponentJoin::QB_JOIN_INNER: {
      uint64_t min = 0xFFFFFFFFFFFFFFFF;
      for (size_t i = 0; i < sources_.size(); ++i) {
        qbCollection src = sources_[i];
        uint64_t maybe_min = src->count(&src->interface);
        if (maybe_min < min) {
          min = maybe_min;
          source = src;
        }
      }
    } break;
    case qbComponentJoin::QB_JOIN_LEFT:
      source = sources_[0];
    break;
    case qbComponentJoin::QB_JOIN_CROSS: {
      uint64_t* max_counts =
          (uint64_t*)alloca(sizeof(uint64_t) * sources_.size());
      uint64_t* indices =
          (uint64_t*)alloca(sizeof(uint64_t) * sources_.size());
      uint8_t** keys = (uint8_t**)alloca(sizeof(uint8_t*) * sources_.size());
      uint8_t** values = (uint8_t**)alloca(sizeof(uint8_t*) * sources_.size());

      memset(indices, 0, sizeof(uint64_t) * sources_.size());
      uint32_t indices_to_inc = 1;
      uint32_t max_index = 1 << sources_.size();
      for (size_t i = 0; i < sources_.size(); ++i) {
        keys[i] = sources_[i]->keys.data(&sources_[i]->interface);
        values[i] = sources_[i]->values.data(&sources_[i]->interface);
        max_counts[i] = sources_[i]->count(&sources_[i]->interface);
        indices[i] = 0;
      }

      while (indices_to_inc < max_index) {
        bool reached_max = false;
        size_t max_src = 0;
        for (size_t i = 0; i < sources_.size(); ++i) {
          reached_max |= indices[i] == max_counts[i];
          if (indices[i] == max_counts[i]) {
            max_src = i;
            continue;
          }

          qbCollection src = sources_[i];
          uint64_t index = indices[i];
          void* k =
              (void*)(keys[i] + src->keys.offset + index * src->keys.stride);
          void* v =
              (void*)(values[i] + src->values.offset + index * src->values.stride);
          CopyToElement(k, v, index, &elements_[i]);

          indices[i] += (1 << i) & indices_to_inc ? 1 : 0;
        }

        if (reached_max) {
          ++indices_to_inc;
          indices[max_src] = 0;
        }
        transform_(elements_data_.data(), sink_interfaces_.data(), f);
      }
    } return;
  }

  const uint64_t count = source->count(&source->interface);
  const uint8_t* keys = source->keys.data(&source->interface);
  switch(join_) {
    case qbComponentJoin::QB_JOIN_LEFT:
    case qbComponentJoin::QB_JOIN_INNER: {
      for(uint64_t i = 0; i < count; ++i) {
        void* k =
            (void*)(keys + source->keys.offset + i * source->keys.stride);

        bool should_continue = false;
        for (size_t j = 0; j < sources_.size(); ++j) {
          qbCollection c = sources_[j];
          void* v = c->interface.by_id(&c->interface, *(qbId*)k);
          if (!v) {
            should_continue = true;
            break;
          }
          CopyToElement(k, v, &elements_[j]);
        }
        if (should_continue) continue;

        transform_(elements_data_.data(), sink_interfaces_.data(), f);
      }
    } break;
    default:
      break;
  }
}

<commit_msg>Only do a cross product when sets are not empty<commit_after>#include "system_impl.h"

SystemImpl::SystemImpl(const qbSystemAttr_& attr, qbSystem system) :
  system_(system), join_(attr.join), user_state_(attr.state),
  transform_(attr.transform),
  callback_(attr.callback) {
  for(auto* component : attr.sinks) {
    sinks_.push_back(component->impl);
    sink_interfaces_.push_back(component->impl->interface);
  }
  for(auto* component : attr.sources) {
    sources_.push_back(component->impl);
    source_interfaces_.push_back(component->impl->interface);
  }

  for(auto* source : sources_) {
    qbElement_ element;
    element.read_buffer = nullptr;
    element.user_buffer = nullptr;
    element.size = source->values.size;
    element.indexed_by = qbIndexedBy::QB_INDEXEDBY_KEY;

    elements_.push_back(element);
  }

  for (size_t i = 0; i < sources_.size(); ++i) {
    auto source = sources_[i];
    auto found = std::find(sinks_.begin(), sinks_.end(), source);
    if (found != sinks_.end()) {
      elements_[i].interface = (*found)->interface;
    }
    elements_data_.push_back(&elements_[i]);
  }
}

SystemImpl* SystemImpl::FromRaw(qbSystem system) {
  return (SystemImpl*)(((char*)system) + sizeof(qbSystem_));
}

void SystemImpl::Run(void* event) {
  size_t source_size = sources_.size();
  size_t sink_size = sinks_.size();
  qbFrame frame;
  frame.event = event;
  frame.state = system_->user_state;

  if (transform_) {
    if (source_size == 0 && sink_size == 0) {
      Run_0_To_0(&frame);
    } else if (source_size == 1 && sink_size == 0) {
      Run_1_To_0(&frame);
    } else if (source_size == 1 && sink_size > 0) {
      Run_1_To_N(&frame);
    } else if (source_size == 0 && sink_size > 0) {
      Run_0_To_N(&frame);
    } else if (source_size > 1) {
      Run_M_To_N(&frame);
    }
  }

  if (callback_) {
    callback_(sink_interfaces_.data(), &frame);
  }
}

void SystemImpl::CopyToElement(void* k, void* v, qbOffset offset,
                               qbElement element) {
  element->id = *(qbId*)k;
  element->read_buffer = v;
  element->offset = offset;
  element->indexed_by = qbIndexedBy::QB_INDEXEDBY_OFFSET;
}

void SystemImpl::CopyToElement(void* k, void* v, qbElement element) {
  element->id = *(qbId*)k;
  element->read_buffer = v;
  element->indexed_by = qbIndexedBy::QB_INDEXEDBY_KEY;
}

void SystemImpl::Run_0_To_0(qbFrame* f) {
  transform_(nullptr, nullptr, f);
}

void SystemImpl::Run_1_To_0(qbFrame* f) {
  qbCollection source = sources_[0];
  uint64_t count = source->count(&source->interface);
  uint8_t* keys = source->keys.data(&source->interface);
  uint8_t* values = source->values.data(&source->interface);

  for(uint64_t i = 0; i < count; ++i) {
    CopyToElement(
        (void*)(keys + source->keys.offset + i * source->keys.stride),
        (void*)(values + source->values.offset + i * source->values.stride),
        i, &elements_.front());
    transform_(elements_data_.data(), nullptr, f);
  }
}

void SystemImpl::Run_0_To_N(qbFrame* f) {
  transform_(nullptr, sink_interfaces_.data(), f);
}

void SystemImpl::Run_1_To_N(qbFrame* f) {
  qbCollection source = sources_[0];
  const uint64_t count = source->count(&source->interface);
  const uint8_t* keys = source->keys.data(&source->interface);
  const uint8_t* values = source->values.data(&source->interface);
  for(uint64_t i = 0; i < count; ++i) {
    CopyToElement(
        (void*)(keys + source->keys.offset + i * source->keys.stride),
        (void*)(values + source->values.offset + i * source->values.stride),
        i, &elements_.front());
    transform_(elements_data_.data(), sink_interfaces_.data(), f);
  }
}

void SystemImpl::Run_M_To_N(qbFrame* f) {
  qbCollection source = sources_[0];
  switch(join_) {
    case qbComponentJoin::QB_JOIN_INNER: {
      uint64_t min = 0xFFFFFFFFFFFFFFFF;
      for (size_t i = 0; i < sources_.size(); ++i) {
        qbCollection src = sources_[i];
        uint64_t maybe_min = src->count(&src->interface);
        if (maybe_min < min) {
          min = maybe_min;
          source = src;
        }
      }
    } break;
    case qbComponentJoin::QB_JOIN_LEFT:
      source = sources_[0];
    break;
    case qbComponentJoin::QB_JOIN_CROSS: {
      uint64_t* max_counts =
          (uint64_t*)alloca(sizeof(uint64_t) * sources_.size());
      uint64_t* indices =
          (uint64_t*)alloca(sizeof(uint64_t) * sources_.size());
      uint8_t** keys = (uint8_t**)alloca(sizeof(uint8_t*) * sources_.size());
      uint8_t** values = (uint8_t**)alloca(sizeof(uint8_t*) * sources_.size());

      memset(indices, 0, sizeof(uint64_t) * sources_.size());
      uint32_t indices_to_inc = 1;
      uint32_t max_index = 1 << sources_.size();
      bool all_empty = true;
      for (size_t i = 0; i < sources_.size(); ++i) {
        keys[i] = sources_[i]->keys.data(&sources_[i]->interface);
        values[i] = sources_[i]->values.data(&sources_[i]->interface);
        max_counts[i] = sources_[i]->count(&sources_[i]->interface);
        indices[i] = 0;
        all_empty &= sources_[i]->count(&sources_[i]->interface) == 0;
      }

      if (all_empty) {
        return;
      }

      while (indices_to_inc < max_index) {
        bool reached_max = false;
        size_t max_src = 0;
        for (size_t i = 0; i < sources_.size(); ++i) {
          reached_max |= indices[i] == max_counts[i];
          if (indices[i] == max_counts[i]) {
            max_src = i;
            continue;
          }

          qbCollection src = sources_[i];
          uint64_t index = indices[i];
          void* k =
              (void*)(keys[i] + src->keys.offset + index * src->keys.stride);
          void* v =
              (void*)(values[i] + src->values.offset + index * src->values.stride);
          CopyToElement(k, v, index, &elements_[i]);

          indices[i] += (1 << i) & indices_to_inc ? 1 : 0;
        }

        if (reached_max) {
          ++indices_to_inc;
          indices[max_src] = 0;
        }
        transform_(elements_data_.data(), sink_interfaces_.data(), f);
      }
    } return;
  }

  const uint64_t count = source->count(&source->interface);
  const uint8_t* keys = source->keys.data(&source->interface);
  switch(join_) {
    case qbComponentJoin::QB_JOIN_LEFT:
    case qbComponentJoin::QB_JOIN_INNER: {
      for(uint64_t i = 0; i < count; ++i) {
        void* k =
            (void*)(keys + source->keys.offset + i * source->keys.stride);

        bool should_continue = false;
        for (size_t j = 0; j < sources_.size(); ++j) {
          qbCollection c = sources_[j];
          void* v = c->interface.by_id(&c->interface, *(qbId*)k);
          if (!v) {
            should_continue = true;
            break;
          }
          CopyToElement(k, v, &elements_[j]);
        }
        if (should_continue) continue;

        transform_(elements_data_.data(), sink_interfaces_.data(), f);
      }
    } break;
    default:
      break;
  }
}

<|endoftext|>


<commit_before>/*-----------------------------------------------------------------------------
 This source file is part of Hopsan NG

 Copyright (c) 2011
    Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
    Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack

 This file is provided "as is", with no guarantee or warranty for the
 functionality or reliability of the contents. All contents in this file is
 the original work of the copyright holders at the Division of Fluid and
 Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
 redistributing any part of this file is prohibited without explicit
 permission from the copyright holders.
-----------------------------------------------------------------------------*/

//!
//! @file   ParameterSettingsLayout.cpp
//! @author Björn Eriksson <bjorn.eriksson@liu.se>
//! @date   2010-03-01
//!
//! @brief Contains a Parameter Settings dialog class for changing parameter properties in components and systems
//!
//$Id$

#include "ParameterSettingsLayout.h"
#include "Utilities/GUIUtilities.h"
#include "GUIObjects/GUIModelObject.h"
#include "GUIObjects/GUIContainerObject.h"

ParameterSettingsLayout::ParameterSettingsLayout(const CoreParameterData &rParameterData, ModelObject *pModelObject, QWidget *pParent) : QGridLayout(pParent)
{
    mpModelObject = pModelObject;
    mParameterType = rParameterData.mType;

    // Set name label
    mName = rParameterData.mName;
    mNameLabel.setText(parseVariableDescription(mName));
    mNameLabel.setMinimumWidth(10);
    mNameLabel.setMaximumWidth(100);
    mNameLabel.adjustSize();
    mNameLabel.setAlignment(Qt::AlignVCenter | Qt::AlignRight);

    // Set description label
    mDescriptionLabel.setMinimumWidth(100);
    mDescriptionLabel.setMaximumWidth(1000);
    mDescriptionLabel.setText(rParameterData.mDescription);
    //mDescriptionNameLabel.setWordWrap(true);
    mDescriptionLabel.adjustSize();

    // Set unit label
    mUnitLabel.setMinimumWidth(50);
    mUnitLabel.setMaximumWidth(50);
    mUnitLabel.setText(parseVariableUnit(rParameterData.mUnit));

    // Set value line editd
    mValueLineEdit.setMinimumWidth(100);
    mValueLineEdit.setMaximumWidth(100);
    mValueLineEdit.setText(rParameterData.mValue);

    // Set tool buttons
    mResetDefaultToolButton.setIcon(QIcon(QString(ICONPATH) + "Hopsan-ResetDefault.png"));
    mResetDefaultToolButton.setToolTip("Reset Default Value");

    mSystemParameterToolButton.setIcon(QIcon(QString(ICONPATH) + "Hopsan-SystemParameter.png"));
    mSystemParameterToolButton.setToolTip("Map To System Parameter");

    // If dynamic parameter add switch button
    if (rParameterData.mIsDynamic)
    {
        bool checked=false;
        //mDynamicEnabledCheckBox.setText("Dynamic");
        mDynamicEnabledCheckBox.setToolTip("Make Port (Experimental)");
        if (mpModelObject->getPort(rParameterData.mName) != 0)
        {
            checked=true;
        }
        mDynamicEnabledCheckBox.setChecked(checked);
        addWidget(&mDynamicEnabledCheckBox, 0, 0);

        //! @todo if parmeter dissabled (connected from outside) make entire ParameterLayout gray or locked (except for the checkbox)
    }

    // Add lables, edits and buttons
    addWidget(&mDescriptionLabel, 0, 1);
    addWidget(&mNameLabel, 0, 2);
    addWidget(&mValueLineEdit, 0, 3);
    addWidget(&mUnitLabel, 0, 4);
    addWidget(&mResetDefaultToolButton, 0, 5);
    addWidget(&mSystemParameterToolButton, 0, 6);

    // Determine value text color
    pickValueTextColor();

    // Connect signals to buttons
    connect(&mResetDefaultToolButton, SIGNAL(clicked()), this, SLOT(setDefaultValue()));
    connect(&mSystemParameterToolButton, SIGNAL(clicked()), this, SLOT(showListOfSystemParameters()));
    connect(&mValueLineEdit, SIGNAL(textChanged(QString)), this, SLOT(pickValueTextColor()));
    connect(&mDynamicEnabledCheckBox, SIGNAL(toggled(bool)), this, SLOT(makePort(bool)));
}

//! @brief Returns the actual parameter name, not the fancy display name
QString ParameterSettingsLayout::getDataName()
{
    return mName;
}

double ParameterSettingsLayout::getDataValue()
{
    return mValueLineEdit.text().toDouble();
}

QString ParameterSettingsLayout::getDataValueTxt()
{
    return mValueLineEdit.text();
}

void ParameterSettingsLayout::setDataValueTxt(QString valueTxt)
{
    mValueLineEdit.setText(valueTxt);
}

//! @brief Sets the value in the text field to the default parameter value
void ParameterSettingsLayout::setDefaultValue()
{
    if(mpModelObject)
    {
        QString defaultText = mpModelObject->getDefaultParameterValue(mName);
        if(defaultText != QString())
            mValueLineEdit.setText(defaultText);
        pickValueTextColor();
    }
}

void ParameterSettingsLayout::showListOfSystemParameters()
{
    QMenu menu;
    QMap<QAction*, QString> actionParamMap;

    QVector<CoreParameterData> paramDataVector;
    mpModelObject->getParentContainerObject()->getParameters(paramDataVector);

    for (int i=0; i<paramDataVector.size(); ++i)
    {
        QAction *tempAction = menu.addAction(paramDataVector[i].mName+" = "+paramDataVector[i].mValue);
        tempAction->setIconVisibleInMenu(false);
        actionParamMap.insert(tempAction, paramDataVector[i].mName);
    }

    QCursor cursor;
    QAction *selectedAction = menu.exec(cursor.pos());

    QString parNameString = actionParamMap.value(selectedAction);
    if(!parNameString.isEmpty())
    {
        mValueLineEdit.setText(parNameString);
    }
}

void ParameterSettingsLayout::makePort(bool isPort)
{
    if (isPort)
    {
        mpModelObject->createRefreshExternalDynamicParameterPort(mName);
    }
    else
    {
        mpModelObject->removeExternalPort(mName);
    }
}

void ParameterSettingsLayout::pickValueTextColor()
{
    if(mpModelObject)
    {
        if(mValueLineEdit.text() == mpModelObject->getDefaultParameterValue(mName))
        {
            QPalette palette( mValueLineEdit.palette() );
            palette.setColor( QPalette::Text, QColor("gray") );
            mValueLineEdit.setPalette(palette);
        }
        else
        {
            QPalette palette( mValueLineEdit.palette() );
            palette.setColor( QPalette::Text, QColor("black") );
            mValueLineEdit.setPalette(palette);
        }
    }
}

//! @brief Verifies that a parameter value does not begin with a number but still contains illegal characters.
//! @note This is a temporary solution. It shall be removed when parsing equations as parameters works.
//! @param value String with parameter that shall be verified
bool ParameterSettingsLayout::cleanAndVerifyParameterValue()
{
    QString value=mValueLineEdit.text();
    QStringList sysParamNames = mpModelObject->getParentContainerObject()->getParameterNames();
    QString error;

    bool isok = verifyParameterValue(value, mParameterType, sysParamNames, error);

    if(isok)
    {
        // Set corrected text
        mValueLineEdit.setText(value);
    }
    else
    {
        QMessageBox::critical(this->parentWidget(), "Error", error.append(" Resetting parameter value!"));
    }

    return isok;
}
<commit_msg>Made value lineedits for externaly connected parameters disabled. Related to #479<commit_after>/*-----------------------------------------------------------------------------
 This source file is part of Hopsan NG

 Copyright (c) 2011
    Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
    Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack

 This file is provided "as is", with no guarantee or warranty for the
 functionality or reliability of the contents. All contents in this file is
 the original work of the copyright holders at the Division of Fluid and
 Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
 redistributing any part of this file is prohibited without explicit
 permission from the copyright holders.
-----------------------------------------------------------------------------*/

//!
//! @file   ParameterSettingsLayout.cpp
//! @author Björn Eriksson <bjorn.eriksson@liu.se>
//! @date   2010-03-01
//!
//! @brief Contains a Parameter Settings dialog class for changing parameter properties in components and systems
//!
//$Id$

#include "ParameterSettingsLayout.h"
#include "Utilities/GUIUtilities.h"
#include "GUIObjects/GUIModelObject.h"
#include "GUIObjects/GUIContainerObject.h"
#include "GUIPort.h"

ParameterSettingsLayout::ParameterSettingsLayout(const CoreParameterData &rParameterData, ModelObject *pModelObject, QWidget *pParent) : QGridLayout(pParent)
{
    mpModelObject = pModelObject;
    mParameterType = rParameterData.mType;

    // Set name label
    mName = rParameterData.mName;
    mNameLabel.setText(parseVariableDescription(mName));
    mNameLabel.setMinimumWidth(10);
    mNameLabel.setMaximumWidth(100);
    mNameLabel.adjustSize();
    mNameLabel.setAlignment(Qt::AlignVCenter | Qt::AlignRight);

    // Set description label
    mDescriptionLabel.setMinimumWidth(100);
    mDescriptionLabel.setMaximumWidth(1000);
    mDescriptionLabel.setText(rParameterData.mDescription);
    //mDescriptionNameLabel.setWordWrap(true);
    mDescriptionLabel.adjustSize();

    // Set unit label
    mUnitLabel.setMinimumWidth(50);
    mUnitLabel.setMaximumWidth(50);
    mUnitLabel.setText(parseVariableUnit(rParameterData.mUnit));

    // Set value line editd
    mValueLineEdit.setMinimumWidth(100);
    mValueLineEdit.setMaximumWidth(100);
    mValueLineEdit.setText(rParameterData.mValue);

    // Set tool buttons
    mResetDefaultToolButton.setIcon(QIcon(QString(ICONPATH) + "Hopsan-ResetDefault.png"));
    mResetDefaultToolButton.setToolTip("Reset Default Value");

    mSystemParameterToolButton.setIcon(QIcon(QString(ICONPATH) + "Hopsan-SystemParameter.png"));
    mSystemParameterToolButton.setToolTip("Map To System Parameter");

    // If dynamic parameter add switch button
    if (rParameterData.mIsDynamic)
    {
        bool checked=false;
        //mDynamicEnabledCheckBox.setText("Dynamic");
        mDynamicEnabledCheckBox.setToolTip("Make Port (Experimental)");
        Port *pPort = mpModelObject->getPort(rParameterData.mName);
        if ( pPort != 0)
        {
            checked=true;

            // If the port exist and is connected then show in value editor that value will not be used
            // NOTE! We cant us "isEnabled from core since it will not be reset until a new simulation is run"
            //! @todo maybe dissable is not best way, you may want to change value without having to dissconnect first.
            if (pPort->isConnected())
            {
                mValueLineEdit.setEnabled(false);
            }
        }
        mDynamicEnabledCheckBox.setChecked(checked);
        addWidget(&mDynamicEnabledCheckBox, 0, 0);
    }

    // Add lables, edits and buttons
    addWidget(&mDescriptionLabel, 0, 1);
    addWidget(&mNameLabel, 0, 2);
    addWidget(&mValueLineEdit, 0, 3);
    addWidget(&mUnitLabel, 0, 4);
    addWidget(&mResetDefaultToolButton, 0, 5);
    addWidget(&mSystemParameterToolButton, 0, 6);

    // Determine value text color
    pickValueTextColor();

    // Connect signals to buttons
    connect(&mResetDefaultToolButton, SIGNAL(clicked()), this, SLOT(setDefaultValue()));
    connect(&mSystemParameterToolButton, SIGNAL(clicked()), this, SLOT(showListOfSystemParameters()));
    connect(&mValueLineEdit, SIGNAL(textChanged(QString)), this, SLOT(pickValueTextColor()));
    connect(&mDynamicEnabledCheckBox, SIGNAL(toggled(bool)), this, SLOT(makePort(bool)));
}

//! @brief Returns the actual parameter name, not the fancy display name
QString ParameterSettingsLayout::getDataName()
{
    return mName;
}

double ParameterSettingsLayout::getDataValue()
{
    return mValueLineEdit.text().toDouble();
}

QString ParameterSettingsLayout::getDataValueTxt()
{
    return mValueLineEdit.text();
}

void ParameterSettingsLayout::setDataValueTxt(QString valueTxt)
{
    mValueLineEdit.setText(valueTxt);
}

//! @brief Sets the value in the text field to the default parameter value
void ParameterSettingsLayout::setDefaultValue()
{
    if(mpModelObject)
    {
        QString defaultText = mpModelObject->getDefaultParameterValue(mName);
        if(defaultText != QString())
            mValueLineEdit.setText(defaultText);
        pickValueTextColor();
    }
}

void ParameterSettingsLayout::showListOfSystemParameters()
{
    QMenu menu;
    QMap<QAction*, QString> actionParamMap;

    QVector<CoreParameterData> paramDataVector;
    mpModelObject->getParentContainerObject()->getParameters(paramDataVector);

    for (int i=0; i<paramDataVector.size(); ++i)
    {
        QAction *tempAction = menu.addAction(paramDataVector[i].mName+" = "+paramDataVector[i].mValue);
        tempAction->setIconVisibleInMenu(false);
        actionParamMap.insert(tempAction, paramDataVector[i].mName);
    }

    QCursor cursor;
    QAction *selectedAction = menu.exec(cursor.pos());

    QString parNameString = actionParamMap.value(selectedAction);
    if(!parNameString.isEmpty())
    {
        mValueLineEdit.setText(parNameString);
    }
}

void ParameterSettingsLayout::makePort(bool isPort)
{
    if (isPort)
    {
        mpModelObject->createRefreshExternalDynamicParameterPort(mName);
    }
    else
    {
        mpModelObject->removeExternalPort(mName);
    }
}

void ParameterSettingsLayout::pickValueTextColor()
{
    if(mpModelObject)
    {
        if(mValueLineEdit.text() == mpModelObject->getDefaultParameterValue(mName))
        {
            QPalette palette( mValueLineEdit.palette() );
            palette.setColor( QPalette::Text, QColor("gray") );
            mValueLineEdit.setPalette(palette);
        }
        else
        {
            QPalette palette( mValueLineEdit.palette() );
            palette.setColor( QPalette::Text, QColor("black") );
            mValueLineEdit.setPalette(palette);
        }
    }
}

//! @brief Verifies that a parameter value does not begin with a number but still contains illegal characters.
//! @note This is a temporary solution. It shall be removed when parsing equations as parameters works.
//! @param value String with parameter that shall be verified
bool ParameterSettingsLayout::cleanAndVerifyParameterValue()
{
    QString value=mValueLineEdit.text();
    QStringList sysParamNames = mpModelObject->getParentContainerObject()->getParameterNames();
    QString error;

    bool isok = verifyParameterValue(value, mParameterType, sysParamNames, error);

    if(isok)
    {
        // Set corrected text
        mValueLineEdit.setText(value);
    }
    else
    {
        QMessageBox::critical(this->parentWidget(), "Error", error.append(" Resetting parameter value!"));
    }

    return isok;
}
<|endoftext|>


<commit_before>/*
 * Author: Henry Bruce <scott.r.ware@intel.com>
 * Copyright (c) 2015 Intel Corporation.
 *
 * 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 <t6713.h>

namespace upm {

    T6713::T6713 (int bus)
    {
        i2c = new mraa::I2c(bus);
        status = mraa::SUCCESS;
    }

    T6713::~T6713()
    {
        delete i2c;
    }

    bool T6713::isConfigured()
    {
        return status == mraa::SUCCESS;
    }

    const char* T6713::getModuleName()
    {
        return "t6713";
    }

    uint16_t T6713::getPpm ()
    {
        return 10;
    }

}
<commit_msg>t6713: Added i2c address<commit_after>/*
 * Author: Henry Bruce <scott.r.ware@intel.com>
 * Copyright (c) 2015 Intel Corporation.
 *
 * 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 <t6713.h>

#define T6713_ADDR 0x15

namespace upm {

    T6713::T6713 (int bus)
    {
        i2c = new mraa::I2c(bus);
        status = i2c->address(T6713_ADDR);
    }

    T6713::~T6713()
    {
        delete i2c;
    }

    bool T6713::isConfigured()
    {
        return status == mraa::SUCCESS;
    }

    const char* T6713::getModuleName()
    {
        return "t6713";
    }

    uint16_t T6713::getPpm ()
    {
        return 10;
    }

}
<|endoftext|>


<commit_before>#include <NetClient.h>
#include <hydra/component/meshcomponent.hpp>

void NetClient::_sendUpdatePacket() {
	if (this->_np.entptr) {
		ClientUpdatePacket cpup;
		Hydra::Component::TransformComponent* tc = this->_np.entptr->getComponent<Hydra::Component::TransformComponent>();
		cpup.ti.pos = tc->getPosition();
		cpup.ti.scale = tc->getScale();
		cpup.ti.rot = tc->getRotation();
		cpup.h.type = PacketType::ClientUpdate;
		cpup.h.len = sizeof(ClientUpdatePacket);

		this->_tcp.send(&cpup, cpup.h.len);
	}
}
HYDRA_API void NetClient::sendEntity(Hydra::World::IEntity * ent) {
	nlohmann::json json;
	ent->serialize(json);
	std::vector<uint8_t> vec = json.to_msgpack(json);
	ClientSpawnEntityPacket* packet = new ClientSpawnEntityPacket();
	packet->h.type = PacketType::ClientSpawnEntity;
	packet->size = vec.size();
	packet->h.len = packet->getSize();

	char* result = new char[sizeof(ClientSpawnEntityPacket) + vec.size() * sizeof(uint8_t)];

	memcpy(result, packet, sizeof(ClientSpawnEntityPacket));
	memcpy(result + sizeof(ClientSpawnEntityPacket), vec.data(), vec.size() * sizeof(uint8_t));

	this->_tcp.send(result, sizeof(ClientSpawnEntityPacket) + vec.size() * sizeof(uint8_t));
	//this->_tcp.send(packet, sizeof(ClientSpawnEntityPacket)); // DATA SNED
	//this->_tcp.send(vec.data(), vec.size() * sizeof(uint8_t)); // DATA SKJICJIK

	delete[] result;
	delete packet;
}

void NetClient::_resolvePackets(Hydra::World::IWorld* world) {
	std::vector<Packet*> packets = this->_tcp.receiveData();
	Hydra::Component::TransformComponent* tc;
	std::vector<std::shared_ptr<Hydra::World::IEntity>> children;
	std::shared_ptr<Hydra::World::IEntity> ent;
	for (size_t i = 0; i < packets.size(); i++) {
		switch (packets[i]->h.type) {
		case PacketType::ServerInitialize:
			children = world->getWorldRoot()->getChildren();
			for (size_t i = 0; i < children.size(); i++) {
				if (children[i]->getName() == "Player") {
					this->_np.entptr = children[i].get();
					break;
				}
			}
			this->_np.entID = ((ServerInitializePacket*)packets[i])->entityid;
			this->_np.entptr->setID(this->_np.entID);
			tc = this->_np.entptr->getComponent<Hydra::Component::TransformComponent>();
			tc->setPosition(((ServerInitializePacket*)packets[i])->ti.pos);
			tc->setRotation(((ServerInitializePacket*)packets[i])->ti.rot);
			tc->setScale(((ServerInitializePacket*)packets[i])->ti.scale);
			//ent = world->createEntity("JagArEttSkott");
			//ent->addComponent<Hydra::Component::TransformComponent>();
			//this->_sendEntity(ent.get()); // KOLLAR SPAWN ENTITYPACKET OM DET FUNGERAR GUCCI
			break;

		case PacketType::ServerUpdate:
			this->_updateWorld(world, packets[i]);
			break;
		case PacketType::ServerPlayer:
			this->_addPlayer(world, packets[i]);
			break;
		case PacketType::ServerSpawnEntity:
			this->_resolveServerSpawnEntityPacket(world, (ServerSpawnEntityPacket*)packets[i]);
			break;
		case PacketType::ServerDeleteEntity:
			this->_resolveServerDeletePacket(world, (ServerDeletePacket*)packets[i]);
			break;
		}
	}

	for (size_t i = 0; i < packets.size(); i++) {
		delete packets[i];
	}
}

HYDRA_API void NetClient::_resolveServerSpawnEntityPacket(Hydra::World::IWorld * world, ServerSpawnEntityPacket* entPacket) {
	nlohmann::json json;
	std::vector<uint8_t> vec;
	for (size_t i = 0; i < entPacket->size; i++) {
		vec.push_back(((uint8_t*)entPacket->data)[i]);
	}
	json = json.from_msgpack(vec);
	std::shared_ptr<Hydra::World::IEntity> ent = world->createEntity("SERVER CREATED (ERROR)");
	ent->deserialize(json);
	ent->setID(entPacket->id);
}

HYDRA_API void NetClient::_resolveServerDeletePacket(Hydra::World::IWorld* world, ServerDeletePacket* delPacket) {
	std::vector<std::shared_ptr<Hydra::World::IEntity>> children = world->getWorldRoot()->getChildren();
	for (size_t i = 0; i < children.size(); i++) {
		if (children[i]->getID() == delPacket->id) {
			children[i]->markDead();
			break;
		}
	}
}

HYDRA_API void NetClient::_updateWorld(Hydra::World::IWorld * world, Packet * updatePacket) {
	std::vector<std::shared_ptr<Hydra::World::IEntity>> children = world->getWorldRoot()->getChildren();
	ServerUpdatePacket* sup = (ServerUpdatePacket*)updatePacket;
	Hydra::Component::TransformComponent* tc;
	for (size_t k = 0; k < sup->nrOfEntUpdates; k++) {
		if (sup->data[k].entityid == this->_np.entID)
			continue;
		for (size_t i = 0; i < children.size(); i++) {
			if (children[i]->getID() == ((ServerUpdatePacket::EntUpdate)sup->data[k]).entityid) {
				tc = children[i]->getComponent<Hydra::Component::TransformComponent>();
				tc->setPosition(((ServerUpdatePacket::EntUpdate)sup->data[k]).ti.pos);
				tc->setRotation(((ServerUpdatePacket::EntUpdate)sup->data[k]).ti.rot);
				tc->setScale(((ServerUpdatePacket::EntUpdate)sup->data[k]).ti.scale);
				break;
			}
		}
	}
}

HYDRA_API void NetClient::_addPlayer(Hydra::World::IWorld * world, Packet * playerPacket) {
	ServerPlayerPacket* spp = (ServerPlayerPacket*)playerPacket;
	char* c = new char[spp->nameLength + 1];
	memcpy(c, spp->name, spp->nameLength);
	c[spp->nameLength] = '\0';

	std::shared_ptr<Hydra::World::IEntity> ent = world->createEntity(c);
	ent->setID(spp->entID);
	Hydra::Component::TransformComponent* tc = ent->addComponent<Hydra::Component::TransformComponent>();
	ent->addComponent<Hydra::Component::MeshComponent>("assets/objects/Table.ATTIC");
	tc->setPosition(spp->ti.pos);
	tc->setRotation(spp->ti.rot);
	tc->setScale(spp->ti.scale);
	delete[] c;
}

bool NetClient::initialize(char* ip, int port) {
	SDLNet_Init();
    if(this->_tcp.initialize(ip, port)) {
        this->_np.entptr = nullptr;
        this->_np.entID = -1;
		return true;
    }
	return false;
}

void NetClient::run(Hydra::World::IWorld* world) {
    {//Receive packets
        this->_resolvePackets(world);
    }

    //SendUpdate packet
    {
        this->_sendUpdatePacket();
    }

    //Nåt
    {

    }
}<commit_msg>show client and server plz<commit_after>#include <NetClient.h>
#include <hydra/component/meshcomponent.hpp>

void NetClient::_sendUpdatePacket() {
	if (this->_np.entptr) {
		ClientUpdatePacket cpup;
		Hydra::Component::TransformComponent* tc = this->_np.entptr->getComponent<Hydra::Component::TransformComponent>();
		cpup.ti.pos = tc->getPosition();
		cpup.ti.scale = tc->getScale();
		cpup.ti.rot = tc->getRotation();
		cpup.h.type = PacketType::ClientUpdate;
		cpup.h.len = sizeof(ClientUpdatePacket);

		this->_tcp.send(&cpup, cpup.h.len);
	}
}
HYDRA_API void NetClient::sendEntity(Hydra::World::IEntity * ent) {
	nlohmann::json json;
	ent->serialize(json);
	std::vector<uint8_t> vec = json.to_msgpack(json);
	ClientSpawnEntityPacket* packet = new ClientSpawnEntityPacket();
	packet->h.type = PacketType::ClientSpawnEntity;
	packet->size = vec.size();
	packet->h.len = packet->getSize();

	char* result = new char[sizeof(ClientSpawnEntityPacket) + vec.size() * sizeof(uint8_t)];

	memcpy(result, packet, sizeof(ClientSpawnEntityPacket));
	memcpy(result + sizeof(ClientSpawnEntityPacket), vec.data(), vec.size() * sizeof(uint8_t));

	this->_tcp.send(result, sizeof(ClientSpawnEntityPacket) + vec.size() * sizeof(uint8_t));
	//this->_tcp.send(packet, sizeof(ClientSpawnEntityPacket)); // DATA SNED
	//this->_tcp.send(vec.data(), vec.size() * sizeof(uint8_t)); // DATA SKJICJIK

	delete[] result;
	delete packet;
}

void NetClient::_resolvePackets(Hydra::World::IWorld* world) {
	std::vector<Packet*> packets = this->_tcp.receiveData();
	Hydra::Component::TransformComponent* tc;
	std::vector<std::shared_ptr<Hydra::World::IEntity>> children;
	std::shared_ptr<Hydra::World::IEntity> ent;
	for (size_t i = 0; i < packets.size(); i++) {
		switch (packets[i]->h.type) {
		case PacketType::ServerInitialize:
			children = world->getWorldRoot()->getChildren();
			for (size_t i = 0; i < children.size(); i++) {
				if (children[i]->getName() == "Player") {
					this->_np.entptr = children[i].get();
					break;
				}
			}
			this->_np.entID = ((ServerInitializePacket*)packets[i])->entityid;
			this->_np.entptr->setID(this->_np.entID);
			tc = this->_np.entptr->getComponent<Hydra::Component::TransformComponent>();
			tc->setPosition(((ServerInitializePacket*)packets[i])->ti.pos);
			tc->setRotation(((ServerInitializePacket*)packets[i])->ti.rot);
			tc->setScale(((ServerInitializePacket*)packets[i])->ti.scale);
			//ent = world->createEntity("JagArEttSkott");
			//ent->addComponent<Hydra::Component::TransformComponent>();
			//this->_sendEntity(ent.get()); // KOLLAR SPAWN ENTITYPACKET OM DET FUNGERAR GUCCI
			break;

		case PacketType::ServerUpdate:
			if(i == packets.size() - 1)
				this->_updateWorld(world, packets[i]);
			break;
		case PacketType::ServerPlayer:
			this->_addPlayer(world, packets[i]);
			break;
		case PacketType::ServerSpawnEntity:
			this->_resolveServerSpawnEntityPacket(world, (ServerSpawnEntityPacket*)packets[i]);
			break;
		case PacketType::ServerDeleteEntity:
			this->_resolveServerDeletePacket(world, (ServerDeletePacket*)packets[i]);
			break;
		}
	}

	for (size_t i = 0; i < packets.size(); i++) {
		delete packets[i];
	}
}

HYDRA_API void NetClient::_resolveServerSpawnEntityPacket(Hydra::World::IWorld * world, ServerSpawnEntityPacket* entPacket) {
	nlohmann::json json;
	std::vector<uint8_t> vec;
	for (size_t i = 0; i < entPacket->size; i++) {
		vec.push_back(((uint8_t*)entPacket->data)[i]);
	}
	json = json.from_msgpack(vec);
	std::shared_ptr<Hydra::World::IEntity> ent = world->createEntity("SERVER CREATED (ERROR)");
	ent->deserialize(json);
	ent->setID(entPacket->id);
}

HYDRA_API void NetClient::_resolveServerDeletePacket(Hydra::World::IWorld* world, ServerDeletePacket* delPacket) {
	std::vector<std::shared_ptr<Hydra::World::IEntity>> children = world->getWorldRoot()->getChildren();
	for (size_t i = 0; i < children.size(); i++) {
		if (children[i]->getID() == delPacket->id) {
			children[i]->markDead();
			break;
		}
	}
}

HYDRA_API void NetClient::_updateWorld(Hydra::World::IWorld * world, Packet * updatePacket) {
	std::vector<std::shared_ptr<Hydra::World::IEntity>> children = world->getWorldRoot()->getChildren();
	ServerUpdatePacket* sup = (ServerUpdatePacket*)updatePacket;
	Hydra::Component::TransformComponent* tc;
	for (size_t k = 0; k < sup->nrOfEntUpdates; k++) {
		if (sup->data[k].entityid == this->_np.entID)
			continue;
		for (size_t i = 0; i < children.size(); i++) {
			if (children[i]->getID() == ((ServerUpdatePacket::EntUpdate)sup->data[k]).entityid) {
				tc = children[i]->getComponent<Hydra::Component::TransformComponent>();
				tc->setPosition(((ServerUpdatePacket::EntUpdate)sup->data[k]).ti.pos);
				tc->setRotation(((ServerUpdatePacket::EntUpdate)sup->data[k]).ti.rot);
				tc->setScale(((ServerUpdatePacket::EntUpdate)sup->data[k]).ti.scale);
				break;
			}
		}
	}
}

HYDRA_API void NetClient::_addPlayer(Hydra::World::IWorld * world, Packet * playerPacket) {
	ServerPlayerPacket* spp = (ServerPlayerPacket*)playerPacket;
	char* c = new char[spp->nameLength + 1];
	memcpy(c, spp->name, spp->nameLength);
	c[spp->nameLength] = '\0';

	std::shared_ptr<Hydra::World::IEntity> ent = world->createEntity(c);
	ent->setID(spp->entID);
	Hydra::Component::TransformComponent* tc = ent->addComponent<Hydra::Component::TransformComponent>();
	ent->addComponent<Hydra::Component::MeshComponent>("assets/objects/Table.ATTIC");
	tc->setPosition(spp->ti.pos);
	tc->setRotation(spp->ti.rot);
	tc->setScale(spp->ti.scale);
	delete[] c;
}

bool NetClient::initialize(char* ip, int port) {
	SDLNet_Init();
    if(this->_tcp.initialize(ip, port)) {
        this->_np.entptr = nullptr;
        this->_np.entID = -1;
		return true;
    }
	return false;
}

void NetClient::run(Hydra::World::IWorld* world) {
    {//Receive packets
        this->_resolvePackets(world);
    }

    //SendUpdate packet
    {
        this->_sendUpdatePacket();
    }

    //Nåt
    {

    }
}<|endoftext|>


<commit_before>#include "stdafx.h"
#include "ScriptsHero.h"

#include "../Entity.h"
#include "../Reporting.h"
#include "../Utils.h"
#include "../World.h"
#include "../Floyd_Level/Tile.h"

void Move(Direction dir, TransformComponent *heroTransform)
{
	heroTransform->prevPosition = heroTransform->position;

	switch (dir)
	{
	case DIR_RIGHT:
		heroTransform->position.x += 1;
		break;
	case DIR_LEFT:
		heroTransform->position.x -= 1;
		break;
	case DIR_UP:
		heroTransform->position.y -= 1;
		break;
	case DIR_DOWN:
		heroTransform->position.y += 1;
		break;
	default:
		Report::Warning("Invalid direction", __LINE__, __FILE__);
		return;
	}

	if (heroTransform->position.y < 0)
	{
		heroTransform->position.y += 1;
	}
	if (heroTransform->position.x < 0)
	{
		heroTransform->position.x += 1;
	}
	// Validate position
}

void Floyd::ScriptHero_OnKeyPressed(Entity *owner, char key)
{
	TransformComponent *heroTransform = owner->GetComponentDirectly<TransformComponent>(CTYPE_TRANSFORM);

	switch (key)
	{
	case KEY_UP:
		Move(DIR_UP, heroTransform);
		break;
	case KEY_LEFT:
		Move(DIR_LEFT, heroTransform);
		break;
	case KEY_DOWN:
		Move(DIR_DOWN, heroTransform);
		break;
	case KEY_RIGHT:
		Move(DIR_RIGHT, heroTransform);
		break;
	default:
		break;
	}
}

/////////////////
//  Collision  //
/////////////////

void Floyd::ScriptHero_OnCollision(World *world, Entity *owner, const Tile *collider)
{
	TransformComponent *heroTransform = owner->GetComponentDirectly<TransformComponent>(CTYPE_TRANSFORM);
	QuestInfoComponent *heroQuestInfo = owner->GetComponentDirectly<QuestInfoComponent>(CTYPE_QUEST_INFO);

	switch (collider->logicalSprite)
	{
	case TILE_WALL:
	case TILE_MONSTER_SPAWN:
	case TILE_EXIT_BLOCK:
		{
			heroTransform->GoToPrevPos();
		}
		break;
	case TILE_TELEPORT:
	case TILE_DREAMS:
		{
			// Hack for bug which causes the hero to be shown the end scene, even if the teleport
			// hasn't been revealed yet.
			if ((collider->logicalSprite == TILE_TELEPORT && collider->sprite == TILE_TELEPORT) ||
				 collider->logicalSprite == TILE_DREAMS)
			{
				world->GetCurrentLevel()->ShowEndscene();
			}
		}
		break;
	case TILE_NPC:
		{
			world->GetCurrentLevel()->ShowNPCscene();
			heroQuestInfo->hasTalkedToNPC = true;
			heroTransform->GoToPrevPos();
		}
		break;
	case TILE_STASH:
	case TILE_SHRINE:
		{
			if (world->IsItemAtPosActive(heroTransform->position))
			{
				Item itemAtPos = world->RetrieveItemAtPos(heroTransform->position);
				owner->GetComponentDirectly<InventoryComponent>(CTYPE_INVENTORY)->AddItem(&itemAtPos);
			}

			if (collider->logicalSprite == TILE_STASH)
			{
				Level *currentLevel = world->GetCurrentLevel();
				if (currentLevel->AreThereMonsterSpawnPositions() && ! currentLevel->HasSpawnedMonstersForLevel())
				{
					currentLevel->SetIsExitDisplayConditionMet(true);
				}
			}

			heroTransform->GoToPrevPos();
		}
		break;
	case TILE_MONSTER:
	case TILE_BOSS:
		{
			auto damageableEntities = world->GetEntitiesWithComponent(CTYPE_STAT);
			for (auto damageable = damageableEntities.begin(); damageable != damageableEntities.end(); ++damageable)
			{
				// Exclude the hero
				if ( ! (*damageable)->GetComponentDirectly<ControllableComponent>(CTYPE_CONTROLLABLE))
				{
					int damage = owner->GetComponentDirectly<StatComponent>(CTYPE_STAT)->damage;
					(*damageable)->GetComponentDirectly<StatComponent>(CTYPE_STAT)->ApplyDamage(damage);
				}
			}

			heroTransform->GoToPrevPos();
		}
		break;
	case TILE_GO_DOWN:
	case TILE_GO_UP:
	case TILE_GO_LEFT:
	case TILE_GO_RIGHT:
		{
			Position entryPos =
				world->GetCurrentLevel()->GetNearestEntryPosForSprite(collider->sprite, heroTransform->position);

			if (entryPos.IsPositive())
			{
				world->TeleportHeroToPosition(entryPos);
			}
		}
		break;
	case TILE_EXIT:
		{
			// Go to next level
			world->GoToNextLevel();
		}
		break;
	case TILE_KILL_BLOCK:
		{
			// Move hero at level beginning
		}
		break;
	}
}<commit_msg>hero returns to starting pos after falling from a cloud<commit_after>#include "stdafx.h"
#include "ScriptsHero.h"

#include "../Entity.h"
#include "../Reporting.h"
#include "../Utils.h"
#include "../World.h"
#include "../Floyd_Level/Tile.h"

void Move(Direction dir, TransformComponent *heroTransform)
{
	heroTransform->prevPosition = heroTransform->position;

	switch (dir)
	{
	case DIR_RIGHT:
		heroTransform->position.x += 1;
		break;
	case DIR_LEFT:
		heroTransform->position.x -= 1;
		break;
	case DIR_UP:
		heroTransform->position.y -= 1;
		break;
	case DIR_DOWN:
		heroTransform->position.y += 1;
		break;
	default:
		Report::Warning("Invalid direction", __LINE__, __FILE__);
		return;
	}

	if (heroTransform->position.y < 0)
	{
		heroTransform->position.y += 1;
	}
	if (heroTransform->position.x < 0)
	{
		heroTransform->position.x += 1;
	}
	// Validate position
}

void Floyd::ScriptHero_OnKeyPressed(Entity *owner, char key)
{
	TransformComponent *heroTransform = owner->GetComponentDirectly<TransformComponent>(CTYPE_TRANSFORM);

	switch (key)
	{
	case KEY_UP:
		Move(DIR_UP, heroTransform);
		break;
	case KEY_LEFT:
		Move(DIR_LEFT, heroTransform);
		break;
	case KEY_DOWN:
		Move(DIR_DOWN, heroTransform);
		break;
	case KEY_RIGHT:
		Move(DIR_RIGHT, heroTransform);
		break;
	default:
		break;
	}
}

/////////////////
//  Collision  //
/////////////////

void Floyd::ScriptHero_OnCollision(World *world, Entity *owner, const Tile *collider)
{
	TransformComponent *heroTransform = owner->GetComponentDirectly<TransformComponent>(CTYPE_TRANSFORM);
	QuestInfoComponent *heroQuestInfo = owner->GetComponentDirectly<QuestInfoComponent>(CTYPE_QUEST_INFO);

	switch (collider->logicalSprite)
	{
	case TILE_WALL:
	case TILE_MONSTER_SPAWN:
	case TILE_EXIT_BLOCK:
		{
			heroTransform->GoToPrevPos();
		}
		break;
	case TILE_TELEPORT:
	case TILE_DREAMS:
		{
			// Hack for bug which causes the hero to be shown the end scene, even if the teleport
			// hasn't been revealed yet.
			if ((collider->logicalSprite == TILE_TELEPORT && collider->sprite == TILE_TELEPORT) ||
				 collider->logicalSprite == TILE_DREAMS)
			{
				world->GetCurrentLevel()->ShowEndscene();
			}
		}
		break;
	case TILE_NPC:
		{
			world->GetCurrentLevel()->ShowNPCscene();
			heroQuestInfo->hasTalkedToNPC = true;
			heroTransform->GoToPrevPos();
		}
		break;
	case TILE_STASH:
	case TILE_SHRINE:
		{
			if (world->IsItemAtPosActive(heroTransform->position))
			{
				Item itemAtPos = world->RetrieveItemAtPos(heroTransform->position);
				owner->GetComponentDirectly<InventoryComponent>(CTYPE_INVENTORY)->AddItem(&itemAtPos);
			}

			if (collider->logicalSprite == TILE_STASH)
			{
				Level *currentLevel = world->GetCurrentLevel();
				if (currentLevel->AreThereMonsterSpawnPositions() && ! currentLevel->HasSpawnedMonstersForLevel())
				{
					currentLevel->SetIsExitDisplayConditionMet(true);
				}
			}

			heroTransform->GoToPrevPos();
		}
		break;
	case TILE_MONSTER:
	case TILE_BOSS:
		{
			auto damageableEntities = world->GetEntitiesWithComponent(CTYPE_STAT);
			for (auto damageable = damageableEntities.begin(); damageable != damageableEntities.end(); ++damageable)
			{
				// Exclude the hero
				if ( ! (*damageable)->GetComponentDirectly<ControllableComponent>(CTYPE_CONTROLLABLE))
				{
					int damage = owner->GetComponentDirectly<StatComponent>(CTYPE_STAT)->damage;
					(*damageable)->GetComponentDirectly<StatComponent>(CTYPE_STAT)->ApplyDamage(damage);
				}
			}

			heroTransform->GoToPrevPos();
		}
		break;
	case TILE_GO_DOWN:
	case TILE_GO_UP:
	case TILE_GO_LEFT:
	case TILE_GO_RIGHT:
		{
			Position entryPos =
				world->GetCurrentLevel()->GetNearestEntryPosForSprite(collider->sprite, heroTransform->position);

			if (entryPos.IsPositive())
			{
				world->TeleportHeroToPosition(entryPos);
			}
		}
		break;
	case TILE_EXIT:
		{
			world->GoToNextLevel();
		}
		break;
	case TILE_KILL_BLOCK:
		{
			Position startingPos = world->GetCurrentLevel()->GetStartingPos();
			world->TeleportHeroToPosition(startingPos);
		}
		break;
	}
}<|endoftext|>


<commit_before>#include "taichi_grid.h"
#include <taichi/system/threading.h>

TC_NAMESPACE_BEGIN

using Block = TestGrid::Block;

MPIEnvironment mpi_env;

TC_TEST("dilated block") {
  if (with_mpi())
    return;
  using Block = TBlock<int, char, TSize3D<8>, 1>;
  Block block(Vector3i(8));

  TC_STATIC_ASSERT(Block::num_nodes == pow<3>(10));
  CHECK(block.linearize_global(Vector3i(7)) == 0);

  int n = 8;
  for (int i = -1; i <= n; i++) {
    for (int j = -1; j <= n; j++) {
      for (int k = -1; k <= n; k++) {
        block.node_global(Vector3i(8) + Vector3i(i, j, k)) = i * j + k;
      }
    }
  }
  for (int i = -1; i <= n; i++) {
    for (int j = -1; j <= n; j++) {
      for (int k = -1; k <= n; k++) {
        CHECK(block.node_global(Vector3i(8) + Vector3i(i, j, k)) == i * j + k);
      }
    }
  }

  using Grid = TaichiGrid<Block>;
  Grid grid;
  Vector3i block_size(8);
  Region3D block_region(Vector3i(7), Vector3i(10));
  Region3D local_grid_region(Vector3i(-1), Vector3i(1) + block_size);

  TArray<3, int> gt(Vector3i(100));
  for (auto b_ind : block_region) {
    auto base_coord = b_ind.get_ipos() * block_size;
    grid.touch(base_coord);
    auto b = grid.get_block_if_exist(base_coord);
    for (auto i : local_grid_region) {
      auto val = rand_int();
      b->node_local(i.get_ipos()) = val;
      gt[base_coord + i.get_ipos()] += val;
    }
  }

  // Do grid exchange here
  grid.advance(
      [](Block &b, TAncestors<Block> &an) { accumulate_dilated_grids(b, an); });

  for (auto b_ind : block_region) {
    auto base_coord = b_ind.get_ipos() * block_size;
    auto b = grid.get_block_if_exist(base_coord);
    for (auto i : local_grid_region) {
      CHECK(gt[base_coord + i.get_ipos()] == b->node_local(i.get_ipos()));
    }
  }
}

TC_TEST("grid_basics") {
  CHECK(product<int, 3>(std::array<int, 3>({2, 3, 4})) == 24);
  CHECK(product<int, 1>(std::array<int, 1>({7})) == 7);

  CHECK(least_pot_bound(7) == 8);
  CHECK(least_pot_bound(0) == 1);
  CHECK(least_pot_bound(1) == 1);
  CHECK(least_pot_bound(1024) == 1024);
  CHECK(least_pot_bound(1023) == 1024);
  CHECK(least_pot_bound(1025) == 2048);

  CHECK(pdep(7, 7) == 7);
  CHECK(pdep(7, 14) == 14);
  CHECK(pdep(3, 14) == 6);
  CHECK(pdep(3, 0) == 0);
  CHECK(pdep(0, 3) == 0);
  CHECK(pdep(1, 3) == 1);
  CHECK(pdep(2, 3) == 2);
  CHECK(pdep(3, 3) == 3);
  CHECK(pdep(1, 21) == 1);
  CHECK(pdep(2, 21) == 4);
  CHECK(pdep(3, 21) == 5);
  CHECK(pdep(4, 21) == 16);

  CHECK(log2int(4) == 2);
  CHECK(log2int(1) == 0);
  CHECK(log2int(8) == 3);
  CHECK(log2int(1ll << 50) == 50);

  CHECK(pot_mask(8) == 255);
}

TC_TEST("grid") {
  if (with_mpi())
    return;
  TestGrid grid;

  constexpr int n = 136;

  CHECK(div_floor(Vector3i(-1, -7, -8), Vector3i(8)) == Vector3i(-1, -1, -1));

  TC_STATIC_ASSERT(n % TestGrid::Block::size[0] == 0);

  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      for (int k = 0; k < n; k++) {
        auto coord = Vector3i(i, j, k);
        grid.touch(coord);
        grid.node(coord).x = i + j * k;
        CHECK(grid.node(coord).x == i + j * k);
      }
    }
  }
  CHECK(grid.root_current.size() == pow<3>((n - 1) / 128 + 1));
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      for (int k = 0; k < n; k++) {
        CHECK(grid.node(Vector3i(i, j, k)).x == i + j * k);
      }
    }
  }
  grid.for_each_block([&](Block &b) {
    for (int i = 0; i < b.num_nodes; i++) {
      b.nodes[i].x += 1;
    }
  });
  grid.for_each_node([&](Block::Node &n) { n.x *= 2; });
  int64 sum = 0;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      for (int k = 0; k < n; k++) {
        auto coord = Vector3i(i, j, k);
        CHECK(grid.node(coord).x == (i + j * k + 1) * 2);
        sum += (int64)(grid.node(Vector3i(i, j, k)).x);
      }
    }
  }
  auto func = [](Block &b) -> int64 {
    int64 sum = 0;
    for (auto n : b.nodes) {
      sum += int64(n.x);
    }
    return sum;
  };
  CHECK(grid.reduce(func, std::plus<int64>(), 0) == sum);
  CHECK(grid.reduce(func, std::plus<int64>()) == sum);
  CHECK(grid.reduce(func) == sum);
  grid.for_each_block([&](Block &b) {
    for (int i = 0; i < Block::size[0]; i++) {
      for (int j = 0; j < Block::size[1]; j++) {
        for (int k = 0; k < Block::size[2]; k++) {
          b.node_local(Vector3i(i, j, k)) =
              (b.base_coord + Vector3i(i, j, k)).template cast<real>();
        }
      }
    }
  });
  grid.advance([&](Block &b, TestGrid::Ancestors &an) {
    auto scratch = TestGrid::GridScratchPad(an);
    auto base_coord = b.base_coord;
    int p = 0;
    for (int i = -1; i <= Block::size[0]; i++) {
      for (int j = -1; j <= Block::size[1]; j++) {
        for (int k = -1; k <= Block::size[2]; k++) {
          auto a = scratch.linearized_data[p];
          auto coord = base_coord + Vector3i(i, j, k);
          if (Vector3i(0) <= coord && coord < Vector3i(n)) {
            auto b = coord.cast<real>();
            CHECK(a == b);
          }
          p++;
        }
      }
    }
  });
}

TC_TEST("block base") {
  {
    // Test at coord 0
    Block base(Vector3i(0));
    int n = 8;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        for (int k = 0; k < n; k++) {
          base.node_global(Vector3i(i, j, k)).x = i + j * k;
        }
      }
    }
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        for (int k = 0; k < n; k++) {
          CHECK(base.node_global(Vector3i(i, j, k)).x == i + j * k);
        }
      }
    }
  }
}

TC_TEST("Propagate") {
  if (with_mpi()) {
    return;
  }
  TestGrid grid;
  grid.touch(Vector3i(0));
  grid.node(Vector3i(0)).x = 100;
  for (int i = 0; i < 10; i++) {
    if (i == 0)
      CHECK(grid.num_active_blocks() == 1);
    if (i == 1)
      CHECK(grid.num_active_blocks() == 4);
    if (i == 2)
      CHECK(grid.num_active_blocks() == 7);
    grid.advance([&](Block &b, TestGrid::Ancestors &an) {
      auto scratch = TestGrid::GridScratchPad(an);
      bool has_non_zero = false;
      for (int i = 0; i < Block::size[0]; i++) {
        for (int j = 0; j < Block::size[1]; j++) {
          for (int k = 0; k < Block::size[2]; k++) {
            int maximum = 0;
            auto update = [&](int di, int dj, int dk) {
              maximum = std::max(maximum,
                                 int(scratch.data[i + di][j + dj][k + dk].x));
            };
            update(0, 0, 0);
            update(1, 0, 0);
            update(-1, 0, 0);
            update(0, 1, 0);
            update(0, -1, 0);
            update(0, 0, 1);
            update(0, 0, -1);
            if (maximum != 0) {
              b.node_local(Vector3i(i, j, k)).x = maximum;
            } else {
              b.kill();
            }
          }
        }
      }
    });
    // TC_P(grid.num_active_blocks());
  }
  CHECK(int(grid.node(Vector3i(0, 10, 0)).x) == 100);
  CHECK(int(grid.node(Vector3i(0, 11, 0)).x) == 0);
  CHECK(int(grid.node(Vector3i(10, 0, 0)).x) == 100);
  CHECK(int(grid.node(Vector3i(11, 0, 0)).x) == 0);
  CHECK(int(grid.node(Vector3i(-10, 0, 0)).x) == 100);
  CHECK(int(grid.node(Vector3i(-11, 0, 0)).x) == 0);
  CHECK(int(grid.node(Vector3i(0, 0, 10)).x) == 100);
  CHECK(int(grid.node(Vector3i(0, 0, 11)).x) == 0);

  CHECK(int(grid.node(Vector3i(0, 5, 5)).x) == 100);
  CHECK(int(grid.node(Vector3i(0, 6, 5)).x) == 0);

  CHECK(grid.root_current.size() == 8);
}

TC_TEST("basic distributed 2") {
  if (!with_mpi())
    return;
  TestGrid grid;
  if (grid.world_size != 2) {
    return;
  }
  if (grid.world_rank == 0) {
    grid.touch(Vector3i(-8, 0, 0));
  } else {
    grid.touch(Vector3i(0, 0, 0));
  }
  // Distributed case
  CHECK(grid.num_active_blocks() == 1);
  grid.fetch_neighbours();
  CHECK(grid.num_active_blocks() == 2);
}

TC_TEST("basic distributed 4") {
  if (!with_mpi())
    return;
  TestGrid grid;
  if (grid.world_size != 4) {
    return;
  }
  grid.touch_if_inside(Vector3i(-8, 0, 0));
  grid.touch_if_inside(Vector3i(-8, 0, -8));
  grid.touch_if_inside(Vector3i(0, 0, 0));
  grid.touch_if_inside(Vector3i(0, 0, -8));
  // Distributed case
  CHECK(grid.num_active_blocks() == 1);
  // grid.fetch_neighbours();
  // CHECK(grid.num_active_blocks() == 4);
}

auto test_mpi = [](const std::vector<std::string> &param) {
  if (!with_mpi()) {
    TC_ERROR("Pls execute this task with mpirun");
  }
  MPI_Init(nullptr, nullptr);
  int world_size = 4, world_rank;
  MPI_Comm_size(MPI_COMM_WORLD, &world_size);
  MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
  TC_P(world_rank);
  MPI_Finalize();
};

TC_REGISTER_TASK(test_mpi);

TC_NAMESPACE_END
<commit_msg>Fixed test<commit_after>#include "taichi_grid.h"
#include <taichi/system/threading.h>

TC_NAMESPACE_BEGIN

using Block = TestGrid::Block;

MPIEnvironment mpi_env;

TC_TEST("dilated block") {
  if (with_mpi())
    return;
  using Block = TBlock<int, char, TSize3D<8>, 1>;
  Block block(Vector3i(8));

  TC_STATIC_ASSERT(Block::num_nodes == pow<3>(10));
  CHECK(block.linearize_global(Vector3i(7)) == 0);

  int n = 8;
  for (int i = -1; i <= n; i++) {
    for (int j = -1; j <= n; j++) {
      for (int k = -1; k <= n; k++) {
        block.node_global(Vector3i(8) + Vector3i(i, j, k)) = i * j + k;
      }
    }
  }
  for (int i = -1; i <= n; i++) {
    for (int j = -1; j <= n; j++) {
      for (int k = -1; k <= n; k++) {
        CHECK(block.node_global(Vector3i(8) + Vector3i(i, j, k)) == i * j + k);
      }
    }
  }

  using Grid = TaichiGrid<Block>;
  Grid grid;
  Vector3i block_size(8);
  Region3D block_region(Vector3i(7), Vector3i(10));
  Region3D local_grid_region(Vector3i(-1), Vector3i(1) + block_size);

  TArray<3, int> gt(Vector3i(100));
  for (auto b_ind : block_region) {
    auto base_coord = b_ind.get_ipos() * block_size;
    grid.touch(base_coord);
    auto b = grid.get_block_if_exist(base_coord);
    for (auto i : local_grid_region) {
      auto val = rand_int();
      b->node_local(i.get_ipos()) = val;
      gt[base_coord + i.get_ipos()] += val;
    }
  }

  // Do grid exchange here
  grid.advance(
      [](Block &b, TAncestors<Block> &an) { accumulate_dilated_grids(b, an); });

  for (auto b_ind : block_region) {
    auto base_coord = b_ind.get_ipos() * block_size;
    auto b = grid.get_block_if_exist(base_coord);
    for (auto i : local_grid_region) {
      CHECK(gt[base_coord + i.get_ipos()] == b->node_local(i.get_ipos()));
    }
  }
}

TC_TEST("grid_basics") {
  CHECK(product<int, 3>(std::array<int, 3>({2, 3, 4})) == 24);
  CHECK(product<int, 1>(std::array<int, 1>({7})) == 7);

  CHECK(least_pot_bound(7) == 8);
  CHECK(least_pot_bound(0) == 1);
  CHECK(least_pot_bound(1) == 1);
  CHECK(least_pot_bound(1024) == 1024);
  CHECK(least_pot_bound(1023) == 1024);
  CHECK(least_pot_bound(1025) == 2048);

  CHECK(pdep(7, 7) == 7);
  CHECK(pdep(7, 14) == 14);
  CHECK(pdep(3, 14) == 6);
  CHECK(pdep(3, 0) == 0);
  CHECK(pdep(0, 3) == 0);
  CHECK(pdep(1, 3) == 1);
  CHECK(pdep(2, 3) == 2);
  CHECK(pdep(3, 3) == 3);
  CHECK(pdep(1, 21) == 1);
  CHECK(pdep(2, 21) == 4);
  CHECK(pdep(3, 21) == 5);
  CHECK(pdep(4, 21) == 16);

  CHECK(log2int(4) == 2);
  CHECK(log2int(1) == 0);
  CHECK(log2int(8) == 3);
  CHECK(log2int(1ll << 50) == 50);

  CHECK(pot_mask(8) == 255);
}

TC_TEST("grid") {
  if (with_mpi())
    return;
  TestGrid grid;

  constexpr int n = 136;

  CHECK(div_floor(Vector3i(-1, -7, -8), Vector3i(8)) == Vector3i(-1, -1, -1));

  TC_STATIC_ASSERT(n % TestGrid::Block::size[0] == 0);

  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      for (int k = 0; k < n; k++) {
        auto coord = Vector3i(i, j, k);
        grid.touch(coord);
        grid.node(coord).x = i + j * k;
        CHECK(grid.node(coord).x == i + j * k);
      }
    }
  }
  CHECK(grid.root_current.size() == pow<3>((n - 1) / 128 + 1));
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      for (int k = 0; k < n; k++) {
        CHECK(grid.node(Vector3i(i, j, k)).x == i + j * k);
      }
    }
  }
  grid.for_each_block([&](Block &b) {
    for (int i = 0; i < b.num_nodes; i++) {
      b.nodes[i].x += 1;
    }
  });
  grid.for_each_node([&](Block::Node &n) { n.x *= 2; });
  int64 sum = 0;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      for (int k = 0; k < n; k++) {
        auto coord = Vector3i(i, j, k);
        CHECK(grid.node(coord).x == (i + j * k + 1) * 2);
        sum += (int64)(grid.node(Vector3i(i, j, k)).x);
      }
    }
  }
  auto func = [](Block &b) -> int64 {
    int64 sum = 0;
    for (auto n : b.nodes) {
      sum += int64(n.x);
    }
    return sum;
  };
  CHECK(grid.reduce(func, std::plus<int64>(), 0) == sum);
  CHECK(grid.reduce(func, std::plus<int64>()) == sum);
  CHECK(grid.reduce(func) == sum);
  grid.for_each_block([&](Block &b) {
    for (int i = 0; i < Block::size[0]; i++) {
      for (int j = 0; j < Block::size[1]; j++) {
        for (int k = 0; k < Block::size[2]; k++) {
          b.node_local(Vector3i(i, j, k)) =
              (b.base_coord + Vector3i(i, j, k)).template cast<real>();
        }
      }
    }
  });
  grid.advance([&](Block &b, TestGrid::Ancestors &an) {
    auto scratch = TestGrid::GridScratchPad(an);
    auto base_coord = b.base_coord;
    int p = 0;
    for (int i = -1; i <= Block::size[0]; i++) {
      for (int j = -1; j <= Block::size[1]; j++) {
        for (int k = -1; k <= Block::size[2]; k++) {
          auto a = scratch.linearized_data[p];
          auto coord = base_coord + Vector3i(i, j, k);
          if (Vector3i(0) <= coord && coord < Vector3i(n)) {
            auto b = coord.cast<real>();
            CHECK(a == b);
          }
          p++;
        }
      }
    }
  });
}

TC_TEST("block base") {
  {
    // Test at coord 0
    Block base(Vector3i(0));
    int n = 8;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        for (int k = 0; k < n; k++) {
          base.node_global(Vector3i(i, j, k)).x = i + j * k;
        }
      }
    }
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        for (int k = 0; k < n; k++) {
          CHECK(base.node_global(Vector3i(i, j, k)).x == i + j * k);
        }
      }
    }
  }
}

TC_TEST("Propagate") {
  if (with_mpi()) {
    return;
  }
  TestGrid grid;
  grid.touch(Vector3i(0));
  grid.node(Vector3i(0)).x = 100;
  for (int i = 0; i < 10; i++) {
    if (i == 0)
      CHECK(grid.num_active_blocks() == 1);
    if (i == 1)
      CHECK(grid.num_active_blocks() == 4);
    if (i == 2)
      CHECK(grid.num_active_blocks() == 7);
    grid.advance([&](Block &b, TestGrid::Ancestors &an) {
      auto scratch = TestGrid::GridScratchPad(an);
      bool has_non_zero = false;
      for (int i = 0; i < Block::size[0]; i++) {
        for (int j = 0; j < Block::size[1]; j++) {
          for (int k = 0; k < Block::size[2]; k++) {
            int maximum = 0;
            auto update = [&](int di, int dj, int dk) {
              maximum = std::max(maximum,
                                 int(scratch.data[i + di][j + dj][k + dk].x));
            };
            update(0, 0, 0);
            update(1, 0, 0);
            update(-1, 0, 0);
            update(0, 1, 0);
            update(0, -1, 0);
            update(0, 0, 1);
            update(0, 0, -1);
            if (maximum != 0) {
              b.node_local(Vector3i(i, j, k)).x = maximum;
              has_non_zero = true;
            }
          }
        }
      }
      if (!has_non_zero) {
        b.kill();
      }
    });
    // TC_P(grid.num_active_blocks());
  }
  CHECK(int(grid.node(Vector3i(0, 10, 0)).x) == 100);
  CHECK(int(grid.node(Vector3i(0, 11, 0)).x) == 0);
  CHECK(int(grid.node(Vector3i(10, 0, 0)).x) == 100);
  CHECK(int(grid.node(Vector3i(11, 0, 0)).x) == 0);
  CHECK(int(grid.node(Vector3i(-10, 0, 0)).x) == 100);
  CHECK(int(grid.node(Vector3i(-11, 0, 0)).x) == 0);
  CHECK(int(grid.node(Vector3i(0, 0, 10)).x) == 100);
  CHECK(int(grid.node(Vector3i(0, 0, 11)).x) == 0);

  CHECK(int(grid.node(Vector3i(0, 5, 5)).x) == 100);
  CHECK(int(grid.node(Vector3i(0, 6, 5)).x) == 0);

  CHECK(grid.root_current.size() == 8);
}

TC_TEST("basic distributed 2") {
  if (!with_mpi())
    return;
  TestGrid grid;
  if (grid.world_size != 2) {
    return;
  }
  if (grid.world_rank == 0) {
    grid.touch(Vector3i(-8, 0, 0));
  } else {
    grid.touch(Vector3i(0, 0, 0));
  }
  // Distributed case
  CHECK(grid.num_active_blocks() == 1);
  grid.fetch_neighbours();
  CHECK(grid.num_active_blocks() == 2);
}

TC_TEST("basic distributed 4") {
  if (!with_mpi())
    return;
  TestGrid grid;
  if (grid.world_size != 4) {
    return;
  }
  grid.touch_if_inside(Vector3i(-8, 0, 0));
  grid.touch_if_inside(Vector3i(-8, 0, -8));
  grid.touch_if_inside(Vector3i(0, 0, 0));
  grid.touch_if_inside(Vector3i(0, 0, -8));
  // Distributed case
  CHECK(grid.num_active_blocks() == 1);
  // grid.fetch_neighbours();
  // CHECK(grid.num_active_blocks() == 4);
}

auto test_mpi = [](const std::vector<std::string> &param) {
  if (!with_mpi()) {
    TC_ERROR("Pls execute this task with mpirun");
  }
  MPI_Init(nullptr, nullptr);
  int world_size = 4, world_rank;
  MPI_Comm_size(MPI_COMM_WORLD, &world_size);
  MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
  TC_P(world_rank);
  MPI_Finalize();
};

TC_REGISTER_TASK(test_mpi);

TC_NAMESPACE_END
<|endoftext|>