<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$ */

// --- Root ---
#include <TClonesArray.h>
#include <TGeoManager.h>
#include <TObjArray.h>
#include <TString.h>
#include <TTree.h>
#include "AliAODCaloCluster.h"
#include "AliAODEvent.h"
#include "AliAnalysisManager.h"
#include "AliCDBEntry.h"
#include "AliCDBManager.h"
#include "AliCaloCalibPedestal.h"
#include "AliEMCALAfterBurnerUF.h"
#include "AliEMCALCalibData.h"
#include "AliEMCALClusterizerNxN.h"
#include "AliEMCALClusterizerv1.h"
#include "AliEMCALDigit.h"
#include "AliEMCALGeometry.h"
#include "AliEMCALRecParam.h"
#include "AliEMCALRecPoint.h"
#include "AliEMCALRecoUtils.h"
#include "AliESDEvent.h"
#include "AliLog.h"

#include "AliAnalysisTaskEMCALClusterizeFast.h"

ClassImp(AliAnalysisTaskEMCALClusterizeFast)

//________________________________________________________________________
AliAnalysisTaskEMCALClusterizeFast::AliAnalysisTaskEMCALClusterizeFast(const char *name)
  : AliAnalysisTaskSE(name),
    fRun(0),
    fDigitsArr(0),
    fClusterArr(0),
    fRecParam(new AliEMCALRecParam),
    fClusterizer(0),
    fUnfolder(0),
    fJustUnfold(kFALSE),
    fGeomName("EMCAL_FIRSTYEARV1"),
    fGeomMatrixSet(kFALSE),
    fLoadGeomMatrices(kFALSE),
    fOCDBpath(),
    fCalibData(0),
    fPedestalData(0),
    fOutputAODBranch(0),
    fOutputAODBrName(),
    fRecoUtils(0)
{
  // Constructor

  fBranchNames     = "ESD:AliESDHeader.,EMCALCells.,AOD:cells";
  for(Int_t i = 0; i < 10; ++i)
    fGeomMatrix[i] = 0;
}

//________________________________________________________________________
AliAnalysisTaskEMCALClusterizeFast::~AliAnalysisTaskEMCALClusterizeFast()
{
  // Destructor.

  delete fDigitsArr;
  delete fClusterizer;
  delete fUnfolder;
  delete fRecoUtils;
}

//-------------------------------------------------------------------
void AliAnalysisTaskEMCALClusterizeFast::UserCreateOutputObjects()
{
  // Create output objects.

  if (!fOutputAODBrName.IsNull()) {
    fOutputAODBranch = new TClonesArray("AliAODCaloCluster", 0);
    fOutputAODBranch->SetName(fOutputAODBrName);
    AddAODBranch("TClonesArray", &fOutputAODBranch);
    AliInfo(Form("Created Branch: %s",fOutputAODBrName.Data()));
  }
}

//________________________________________________________________________
void AliAnalysisTaskEMCALClusterizeFast::UserExec(Option_t *)
{
  // Main loop, called for each event

  // remove the contents of output list set in the previous event
  if (fOutputAODBranch)
    fOutputAODBranch->Clear("C");

  AliESDEvent *esdevent = dynamic_cast<AliESDEvent*>(InputEvent());
  AliAODEvent *aodevent = dynamic_cast<AliAODEvent*>(InputEvent());

  if (!esdevent&&!aodevent) {
    Error("UserExec","Event not available");
    return;
  }

  LoadBranches();

  Init();

  if (fJustUnfold) {
    AliWarning("Unfolding not implemented");
  } else {
    if (esdevent)
      FillDigitsArray(esdevent);
    else
      FillDigitsArray(aodevent);
    fClusterizer->Digits2Clusters("");
    if (esdevent &&fRecoUtils)
      fRecoUtils->FindMatches(esdevent,fClusterArr);
    if (fOutputAODBranch)
      RecPoints2Clusters();
  }
}

//________________________________________________________________________
void AliAnalysisTaskEMCALClusterizeFast::FillDigitsArray(AliAODEvent *event)
{
  // Fill digits from cells.

  fDigitsArr->Clear("C");
  AliAODCaloCells *cells = event->GetEMCALCells();
  Int_t ncells = cells->GetNumberOfCells();
  if (ncells>fDigitsArr->GetSize())
    fDigitsArr->Expand(2*ncells);
  for (Int_t icell = 0, idigit = 0; icell < ncells; ++icell) {
    Double_t cellAmplitude=0, cellTime=0;
    Short_t cellNumber=0;
    if (cells->GetCell(icell, cellNumber, cellAmplitude, cellTime) != kTRUE)
      break;
    AliEMCALDigit *digit = (AliEMCALDigit*) fDigitsArr->New(idigit);
    digit->SetId(cellNumber);
    digit->SetAmplitude(cellAmplitude);
    digit->SetTime(cellTime);
    digit->SetTimeR(cellTime);
    digit->SetIndexInList(idigit);
    digit->SetType(AliEMCALDigit::kHG);
    idigit++;
  }
}

//________________________________________________________________________
void AliAnalysisTaskEMCALClusterizeFast::FillDigitsArray(AliESDEvent *event)
{
  // Fill digits from cells.

  fDigitsArr->Clear("C");
  AliESDCaloCells *cells = event->GetEMCALCells();
  Int_t ncells = cells->GetNumberOfCells();
  if (ncells>fDigitsArr->GetSize())
    fDigitsArr->Expand(2*ncells);
  for (Int_t icell = 0, idigit = 0; icell < ncells; ++icell) {
    Double_t cellAmplitude=0, cellTime=0;
    Short_t cellNumber=0;
    if (cells->GetCell(icell, cellNumber, cellAmplitude, cellTime) != kTRUE)
      break;
    AliEMCALDigit *digit = (AliEMCALDigit*) fDigitsArr->New(idigit);
    digit->SetId(cellNumber);
    digit->SetAmplitude(cellAmplitude);
    digit->SetTime(cellTime);
    digit->SetTimeR(cellTime);
    digit->SetIndexInList(idigit);
    digit->SetType(AliEMCALDigit::kHG);
    idigit++;
  }
}

//________________________________________________________________________________________
void AliAnalysisTaskEMCALClusterizeFast::RecPoints2Clusters()
{
  // Cluster energy, global position, cells and their amplitude fractions are restored.

  AliESDEvent *esdevent = dynamic_cast<AliESDEvent*>(InputEvent());

  Int_t Ncls = fClusterArr->GetEntriesFast();
  for(Int_t i=0, nout=0; i < Ncls; ++i) {
    AliEMCALRecPoint *recpoint = static_cast<AliEMCALRecPoint*>(fClusterArr->At(i));
    Int_t ncells_true = 0;
    const Int_t ncells = recpoint->GetMultiplicity();
    UShort_t   absIds[ncells];
    Double32_t ratios[ncells];
    Int_t *dlist = recpoint->GetDigitsList();
    Float_t *elist = recpoint->GetEnergiesList();

    for (Int_t c = 0; c < ncells; ++c) {
      AliEMCALDigit *digit = static_cast<AliEMCALDigit*>(fDigitsArr->At(dlist[c]));
      absIds[ncells_true] = digit->GetId();
      ratios[ncells_true] = elist[c]/digit->GetAmplitude();
      if (ratios[ncells_true] > 0.001)
        ++ncells_true;
    }

    if (ncells_true < 1) {
      AliWarning("Skipping cluster with no cells");
      continue;
    }

    // calculate new cluster position
    TVector3 gpos;
    Float_t g[3];

    recpoint->EvalGlobalPosition(fRecParam->GetW0(), fDigitsArr);
    recpoint->GetGlobalPosition(gpos);
    gpos.GetXYZ(g);

    AliAODCaloCluster *clus = static_cast<AliAODCaloCluster*>(fOutputAODBranch->New(nout++));
    clus->SetType(AliVCluster::kEMCALClusterv1);
    clus->SetE(recpoint->GetEnergy());
    clus->SetPosition(g);
    clus->SetNCells(ncells_true);
    clus->SetCellsAbsId(absIds);
    clus->SetCellsAmplitudeFraction(ratios);
    clus->SetDispersion(recpoint->GetDispersion());
    clus->SetChi2(-1);                      //not yet implemented
    clus->SetTOF(recpoint->GetTime()) ;     //time-of-flight
    clus->SetNExMax(recpoint->GetNExMax()); //number of local maxima
    Float_t elipAxis[2];
    recpoint->GetElipsAxis(elipAxis);
    clus->SetM02(elipAxis[0]*elipAxis[0]) ;
    clus->SetM20(elipAxis[1]*elipAxis[1]) ;
    clus->SetDistToBadChannel(recpoint->GetDistanceToBadTower());
    if (esdevent && fRecoUtils) {
      Int_t trackIndex = fRecoUtils->GetMatchedTrackIndex(i);
      if(trackIndex >= 0) {
        clus->AddTrackMatched(esdevent->GetTrack(trackIndex));
        if(DebugLevel() > 1)
          AliInfo(Form("Matched Track index %d to new cluster %d\n",trackIndex,i));
      }
    }
  }
}

//________________________________________________________________________________________
void AliAnalysisTaskEMCALClusterizeFast::Init()
{
  //Select clusterization/unfolding algorithm and set all the needed parameters

  AliVEvent * event = InputEvent();
  if (!event) {
    AliWarning("Event not available!!!");
    return;
  }

  if (event->GetRunNumber()==fRun)
    return;
  fRun = event->GetRunNumber();

  if (fJustUnfold){
    // init the unfolding afterburner
    delete fUnfolder;
    fUnfolder = new AliEMCALAfterBurnerUF(fRecParam->GetW0(),fRecParam->GetLocMaxCut());
    return;
  }

  AliCDBManager *cdb = AliCDBManager::Instance();
  if (!cdb->IsDefaultStorageSet() && !fOCDBpath.IsNull())
    cdb->SetDefaultStorage(fOCDBpath);
  if (fRun!=cdb->GetRun())
    cdb->SetRun(fRun);

  AliEMCALGeometry *geometry = AliEMCALGeometry::GetInstance(fGeomName);
  if (!geometry) {
    AliFatal("Geometry not available!!!");
    return;
  }

  if (!fGeomMatrixSet) {
    if (fLoadGeomMatrices) {
      for(Int_t mod=0; mod < (geometry->GetEMCGeometry())->GetNumberOfSuperModules(); ++mod) {
        if(fGeomMatrix[mod]){
          if(DebugLevel() > 2)
            fGeomMatrix[mod]->Print();
          geometry->SetMisalMatrix(fGeomMatrix[mod],mod);
        }
      }
    } else {
      for(Int_t mod=0; mod < geometry->GetEMCGeometry()->GetNumberOfSuperModules(); ++mod) {
        if(event->GetEMCALMatrix(mod)) {
          if(DebugLevel() > 2)
            event->GetEMCALMatrix(mod)->Print();
          geometry->SetMisalMatrix(event->GetEMCALMatrix(mod),mod);
        }
      }
    }
    fGeomMatrixSet=kTRUE;
  }

  // setup digit array if needed
  if (!fDigitsArr) {
    fDigitsArr = new TClonesArray("AliEMCALDigit", 1000);
    fDigitsArr->SetOwner(1);
  }

  // then setup clusterizer
  delete fClusterizer;
  if     (fRecParam->GetClusterizerFlag() == AliEMCALRecParam::kClusterizerv1)
    fClusterizer = new AliEMCALClusterizerv1(geometry);
  else if(fRecParam->GetClusterizerFlag() == AliEMCALRecParam::kClusterizerNxN)
    fClusterizer = new AliEMCALClusterizerNxN(geometry);
  else if(fRecParam->GetClusterizerFlag() > AliEMCALRecParam::kClusterizerNxN) {
   AliEMCALClusterizerNxN *clusterizer = new AliEMCALClusterizerNxN(geometry);
   clusterizer->SetNRowDiff(2);
   clusterizer->SetNColDiff(2);
   fClusterizer = clusterizer;
  } else{
    AliFatal(Form("Clusterizer < %d > not available", fRecParam->GetClusterizerFlag()));
  }
  fClusterizer->InitParameters(fRecParam);
  fClusterizer->SetInputCalibrated(kTRUE);
  if (!fCalibData&&0) {
    AliCDBEntry *entry = static_cast<AliCDBEntry*>(AliCDBManager::Instance()->Get("EMCAL/Calib/Data"));
    if (entry)
      fCalibData =  static_cast<AliEMCALCalibData*>(entry->GetObject());
    if (!fCalibData)
      AliFatal("Calibration parameters not found in CDB!");
  }
  if (!fPedestalData&&0) {
    AliCDBEntry *entry = static_cast<AliCDBEntry*>(AliCDBManager::Instance()->Get("EMCAL/Calib/Pedestals"));
    if (entry)
      fPedestalData =  static_cast<AliCaloCalibPedestal*>(entry->GetObject());
  }
  fClusterizer->SetCalibrationParameters(fCalibData);
  fClusterizer->SetCaloCalibPedestal(fPedestalData);
  fClusterizer->SetDigitsArr(fDigitsArr);
  fClusterizer->SetOutput(0);
  fClusterArr = const_cast<TObjArray *>(fClusterizer->GetRecPoints());
}
<commit_msg>run on AOD branches<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$ */

// --- Root ---
#include <TClonesArray.h>
#include <TGeoManager.h>
#include <TObjArray.h>
#include <TString.h>
#include <TTree.h>
#include "AliAODCaloCluster.h"
#include "AliAODEvent.h"
#include "AliAnalysisManager.h"
#include "AliCDBEntry.h"
#include "AliCDBManager.h"
#include "AliCaloCalibPedestal.h"
#include "AliEMCALAfterBurnerUF.h"
#include "AliEMCALCalibData.h"
#include "AliEMCALClusterizerNxN.h"
#include "AliEMCALClusterizerv1.h"
#include "AliEMCALDigit.h"
#include "AliEMCALGeometry.h"
#include "AliEMCALRecParam.h"
#include "AliEMCALRecPoint.h"
#include "AliEMCALRecoUtils.h"
#include "AliESDEvent.h"
#include "AliLog.h"

#include "AliAnalysisTaskEMCALClusterizeFast.h"

ClassImp(AliAnalysisTaskEMCALClusterizeFast)

//________________________________________________________________________
AliAnalysisTaskEMCALClusterizeFast::AliAnalysisTaskEMCALClusterizeFast(const char *name)
  : AliAnalysisTaskSE(name),
    fRun(0),
    fDigitsArr(0),
    fClusterArr(0),
    fRecParam(new AliEMCALRecParam),
    fClusterizer(0),
    fUnfolder(0),
    fJustUnfold(kFALSE),
    fGeomName("EMCAL_FIRSTYEARV1"),
    fGeomMatrixSet(kFALSE),
    fLoadGeomMatrices(kFALSE),
    fOCDBpath(),
    fCalibData(0),
    fPedestalData(0),
    fOutputAODBranch(0),
    fOutputAODBrName(),
    fRecoUtils(0)
{
  // Constructor

  fBranchNames     = "ESD:AliESDHeader.,EMCALCells. AOD:header,emcalCells";
  for(Int_t i = 0; i < 10; ++i)
    fGeomMatrix[i] = 0;
}

//________________________________________________________________________
AliAnalysisTaskEMCALClusterizeFast::~AliAnalysisTaskEMCALClusterizeFast()
{
  // Destructor.

  delete fDigitsArr;
  delete fClusterizer;
  delete fUnfolder;
  delete fRecoUtils;
}

//-------------------------------------------------------------------
void AliAnalysisTaskEMCALClusterizeFast::UserCreateOutputObjects()
{
  // Create output objects.

  if (!fOutputAODBrName.IsNull()) {
    fOutputAODBranch = new TClonesArray("AliAODCaloCluster", 0);
    fOutputAODBranch->SetName(fOutputAODBrName);
    AddAODBranch("TClonesArray", &fOutputAODBranch);
    AliInfo(Form("Created Branch: %s",fOutputAODBrName.Data()));
  }
}

//________________________________________________________________________
void AliAnalysisTaskEMCALClusterizeFast::UserExec(Option_t *)
{
  // Main loop, called for each event

  // remove the contents of output list set in the previous event
  if (fOutputAODBranch)
    fOutputAODBranch->Clear("C");

  AliESDEvent *esdevent = dynamic_cast<AliESDEvent*>(InputEvent());
  AliAODEvent *aodevent = dynamic_cast<AliAODEvent*>(InputEvent());

  if (!esdevent&&!aodevent) {
    Error("UserExec","Event not available");
    return;
  }

  LoadBranches();

  Init();

  if (fJustUnfold) {
    AliWarning("Unfolding not implemented");
  } else {
    if (esdevent)
      FillDigitsArray(esdevent);
    else
      FillDigitsArray(aodevent);
    fClusterizer->Digits2Clusters("");
    if (esdevent &&fRecoUtils)
      fRecoUtils->FindMatches(esdevent,fClusterArr);
    if (fOutputAODBranch)
      RecPoints2Clusters();
  }
}

//________________________________________________________________________
void AliAnalysisTaskEMCALClusterizeFast::FillDigitsArray(AliAODEvent *event)
{
  // Fill digits from cells.

  fDigitsArr->Clear("C");
  AliAODCaloCells *cells = event->GetEMCALCells();
  Int_t ncells = cells->GetNumberOfCells();
  if (ncells>fDigitsArr->GetSize())
    fDigitsArr->Expand(2*ncells);
  for (Int_t icell = 0, idigit = 0; icell < ncells; ++icell) {
    Double_t cellAmplitude=0, cellTime=0;
    Short_t cellNumber=0;
    if (cells->GetCell(icell, cellNumber, cellAmplitude, cellTime) != kTRUE)
      break;
    AliEMCALDigit *digit = (AliEMCALDigit*) fDigitsArr->New(idigit);
    digit->SetId(cellNumber);
    digit->SetAmplitude(cellAmplitude);
    digit->SetTime(cellTime);
    digit->SetTimeR(cellTime);
    digit->SetIndexInList(idigit);
    digit->SetType(AliEMCALDigit::kHG);
    idigit++;
  }
}

//________________________________________________________________________
void AliAnalysisTaskEMCALClusterizeFast::FillDigitsArray(AliESDEvent *event)
{
  // Fill digits from cells.

  fDigitsArr->Clear("C");
  AliESDCaloCells *cells = event->GetEMCALCells();
  Int_t ncells = cells->GetNumberOfCells();
  if (ncells>fDigitsArr->GetSize())
    fDigitsArr->Expand(2*ncells);
  for (Int_t icell = 0, idigit = 0; icell < ncells; ++icell) {
    Double_t cellAmplitude=0, cellTime=0;
    Short_t cellNumber=0;
    if (cells->GetCell(icell, cellNumber, cellAmplitude, cellTime) != kTRUE)
      break;
    AliEMCALDigit *digit = (AliEMCALDigit*) fDigitsArr->New(idigit);
    digit->SetId(cellNumber);
    digit->SetAmplitude(cellAmplitude);
    digit->SetTime(cellTime);
    digit->SetTimeR(cellTime);
    digit->SetIndexInList(idigit);
    digit->SetType(AliEMCALDigit::kHG);
    idigit++;
  }
}

//________________________________________________________________________________________
void AliAnalysisTaskEMCALClusterizeFast::RecPoints2Clusters()
{
  // Cluster energy, global position, cells and their amplitude fractions are restored.

  AliESDEvent *esdevent = dynamic_cast<AliESDEvent*>(InputEvent());

  Int_t Ncls = fClusterArr->GetEntriesFast();
  for(Int_t i=0, nout=0; i < Ncls; ++i) {
    AliEMCALRecPoint *recpoint = static_cast<AliEMCALRecPoint*>(fClusterArr->At(i));
    Int_t ncells_true = 0;
    const Int_t ncells = recpoint->GetMultiplicity();
    UShort_t   absIds[ncells];
    Double32_t ratios[ncells];
    Int_t *dlist = recpoint->GetDigitsList();
    Float_t *elist = recpoint->GetEnergiesList();

    for (Int_t c = 0; c < ncells; ++c) {
      AliEMCALDigit *digit = static_cast<AliEMCALDigit*>(fDigitsArr->At(dlist[c]));
      absIds[ncells_true] = digit->GetId();
      ratios[ncells_true] = elist[c]/digit->GetAmplitude();
      if (ratios[ncells_true] > 0.001)
        ++ncells_true;
    }

    if (ncells_true < 1) {
      AliWarning("Skipping cluster with no cells");
      continue;
    }

    // calculate new cluster position
    TVector3 gpos;
    Float_t g[3];

    recpoint->EvalGlobalPosition(fRecParam->GetW0(), fDigitsArr);
    recpoint->GetGlobalPosition(gpos);
    gpos.GetXYZ(g);

    AliAODCaloCluster *clus = static_cast<AliAODCaloCluster*>(fOutputAODBranch->New(nout++));
    clus->SetType(AliVCluster::kEMCALClusterv1);
    clus->SetE(recpoint->GetEnergy());
    clus->SetPosition(g);
    clus->SetNCells(ncells_true);
    clus->SetCellsAbsId(absIds);
    clus->SetCellsAmplitudeFraction(ratios);
    clus->SetDispersion(recpoint->GetDispersion());
    clus->SetChi2(-1);                      //not yet implemented
    clus->SetTOF(recpoint->GetTime()) ;     //time-of-flight
    clus->SetNExMax(recpoint->GetNExMax()); //number of local maxima
    Float_t elipAxis[2];
    recpoint->GetElipsAxis(elipAxis);
    clus->SetM02(elipAxis[0]*elipAxis[0]) ;
    clus->SetM20(elipAxis[1]*elipAxis[1]) ;
    clus->SetDistToBadChannel(recpoint->GetDistanceToBadTower());
    if (esdevent && fRecoUtils) {
      Int_t trackIndex = fRecoUtils->GetMatchedTrackIndex(i);
      if(trackIndex >= 0) {
        clus->AddTrackMatched(esdevent->GetTrack(trackIndex));
        if(DebugLevel() > 1)
          AliInfo(Form("Matched Track index %d to new cluster %d\n",trackIndex,i));
      }
    }
  }
}

//________________________________________________________________________________________
void AliAnalysisTaskEMCALClusterizeFast::Init()
{
  //Select clusterization/unfolding algorithm and set all the needed parameters

  AliVEvent * event = InputEvent();
  if (!event) {
    AliWarning("Event not available!!!");
    return;
  }

  if (event->GetRunNumber()==fRun)
    return;
  fRun = event->GetRunNumber();

  if (fJustUnfold){
    // init the unfolding afterburner
    delete fUnfolder;
    fUnfolder = new AliEMCALAfterBurnerUF(fRecParam->GetW0(),fRecParam->GetLocMaxCut());
    return;
  }

  AliCDBManager *cdb = AliCDBManager::Instance();
  if (!cdb->IsDefaultStorageSet() && !fOCDBpath.IsNull())
    cdb->SetDefaultStorage(fOCDBpath);
  if (fRun!=cdb->GetRun())
    cdb->SetRun(fRun);

  AliEMCALGeometry *geometry = AliEMCALGeometry::GetInstance(fGeomName);
  if (!geometry) {
    AliFatal("Geometry not available!!!");
    return;
  }

  if (!fGeomMatrixSet) {
    if (fLoadGeomMatrices) {
      for(Int_t mod=0; mod < (geometry->GetEMCGeometry())->GetNumberOfSuperModules(); ++mod) {
        if(fGeomMatrix[mod]){
          if(DebugLevel() > 2)
            fGeomMatrix[mod]->Print();
          geometry->SetMisalMatrix(fGeomMatrix[mod],mod);
        }
      }
    } else {
      for(Int_t mod=0; mod < geometry->GetEMCGeometry()->GetNumberOfSuperModules(); ++mod) {
        if(event->GetEMCALMatrix(mod)) {
          if(DebugLevel() > 2)
            event->GetEMCALMatrix(mod)->Print();
          geometry->SetMisalMatrix(event->GetEMCALMatrix(mod),mod);
        }
      }
    }
    fGeomMatrixSet=kTRUE;
  }

  // setup digit array if needed
  if (!fDigitsArr) {
    fDigitsArr = new TClonesArray("AliEMCALDigit", 1000);
    fDigitsArr->SetOwner(1);
  }

  // then setup clusterizer
  delete fClusterizer;
  if     (fRecParam->GetClusterizerFlag() == AliEMCALRecParam::kClusterizerv1)
    fClusterizer = new AliEMCALClusterizerv1(geometry);
  else if(fRecParam->GetClusterizerFlag() == AliEMCALRecParam::kClusterizerNxN)
    fClusterizer = new AliEMCALClusterizerNxN(geometry);
  else if(fRecParam->GetClusterizerFlag() > AliEMCALRecParam::kClusterizerNxN) {
   AliEMCALClusterizerNxN *clusterizer = new AliEMCALClusterizerNxN(geometry);
   clusterizer->SetNRowDiff(2);
   clusterizer->SetNColDiff(2);
   fClusterizer = clusterizer;
  } else{
    AliFatal(Form("Clusterizer < %d > not available", fRecParam->GetClusterizerFlag()));
  }
  fClusterizer->InitParameters(fRecParam);
  fClusterizer->SetInputCalibrated(kTRUE);
  if (!fCalibData&&0) {
    AliCDBEntry *entry = static_cast<AliCDBEntry*>(AliCDBManager::Instance()->Get("EMCAL/Calib/Data"));
    if (entry)
      fCalibData =  static_cast<AliEMCALCalibData*>(entry->GetObject());
    if (!fCalibData)
      AliFatal("Calibration parameters not found in CDB!");
  }
  if (!fPedestalData&&0) {
    AliCDBEntry *entry = static_cast<AliCDBEntry*>(AliCDBManager::Instance()->Get("EMCAL/Calib/Pedestals"));
    if (entry)
      fPedestalData =  static_cast<AliCaloCalibPedestal*>(entry->GetObject());
  }
  fClusterizer->SetCalibrationParameters(fCalibData);
  fClusterizer->SetCaloCalibPedestal(fPedestalData);
  fClusterizer->SetDigitsArr(fDigitsArr);
  fClusterizer->SetOutput(0);
  fClusterArr = const_cast<TObjArray *>(fClusterizer->GetRecPoints());
}
<|endoftext|>


<commit_before>  ///////////////////////////////////////////////////////////////////////////
  ///\file AddTaskEMCALPhotonIsolation.C
  ///\brief Configuration of AliAnalysisTaskEMCALPhotonIsolation
  ///
  /// Version to be used in lego train for testing on pp@7TeV
  ///
  /// \author Lucile Ronflette <lucile.ronflette@cern.ch>, SUBATECH, Nantes
  /// \author Davide Francesco Lodato <davide.francesco.lodato@cern.ch>, Utrecht University
  /// \author Marco Marquard <marco.marquard@cern.ch>, University Frankfurt am Main
  ///////////////////////////////////////////////////////////////////////////

AliAnalysisTaskEMCALPhotonIsolation* AddTaskEMCALPhotonIsolation(
                                                                 const char*            periodstr                 = "LHC11c",
                                                                 const char*            ntracks                   = "EmcalTracks",
                                                                 const char*            nclusters                 = "EmcCaloClusters",
                                                                 const UInt_t           pSel                      = AliVEvent::kEMC7,
                                                                 const TString          dType                     = "ESD",
                                                                 const Bool_t	        bHisto                    = kTRUE,
                                                                 const Int_t	        iOutput	  	          = 0,
                                                                 const Bool_t	        bIsMC  	                  = kFALSE,
                                                                 const Bool_t           bMCNormalization          = kFALSE,
                                                                 const Bool_t           bNLMCut                   = kFALSE,
                                                                 const Int_t            NLMCut                    = 0,
                                                                 const Double_t         minPtCutCluster           = 0.3,
                                                                 const Double_t         EtIso                     = 2.,
                                                                 const Int_t            iIsoMethod                = 1,
                                                                 const Int_t            iEtIsoMethod              = 0,
                                                                 const Int_t            iUEMethod                 = 1,
                                                                 const Bool_t           bUseofTPC                 = kFALSE,
                                                                 const Double_t         TMdeta                    = 0.02,
                                                                 const Double_t         TMdphi                    = 0.03,
                                                                 const Bool_t           bTMClusterRejection       = kTRUE,
                                                                 const Bool_t           bTMClusterRejectionInCone = kTRUE,
                                                                 const Float_t          iIsoConeRadius            = 0.4,
                                                                 const Bool_t           iSmearingSS               = kFALSE,
                                                                 const Float_t          iWidthSSsmear             = 0.,
                                                                 const Float_t          iMean_SSsmear             = 0.,
                                                                 const Bool_t           iExtraIsoCuts             = kFALSE,
                                                                 const Bool_t           i_pPb                     = kFALSE,
                                                                 const Bool_t           isQA                      = kFALSE,
                                                                 TString                configBasePath            = "",
                                                                 const Int_t            bWhichToSmear             = 0,
                                                                 const Int_t            minNLM                    = 1
                                                                 )
{

  Printf("Preparing neutral cluster analysis\n");

    // #### Define manager and data container names
  AliAnalysisManager *manager = AliAnalysisManager::GetAnalysisManager();
  if (!manager) {
    ::Error("AddTaskEMCALPhotonIsolation", "No analysis manager to connect to.");
    return NULL;
  }

  printf("Creating container names for cluster analysis\n");
  TString myContName("");
  if(bIsMC)
    myContName = Form("Analysis_Neutrals_MC");
  else
    myContName = Form("Analysis_Neutrals");

  myContName.Append(Form("_TM_%s_CPVe%.2lf_CPVp%.2lf_IsoMet%d_EtIsoMet%d_UEMet%d_TPCbound_%s_IsoConeR%.1f_NLMCut_%s_minNLM%d_maxNLM%d_SSsmear_%s_Width%.3f_Mean_%.3f_PureIso_%s_WhichSmear_%d",bTMClusterRejection? "On" :"Off", TMdeta , TMdphi ,iIsoMethod,iEtIsoMethod,iUEMethod,bUseofTPC ? "Yes" : "No",iIsoConeRadius,bNLMCut ? "On": "Off",minNLM, NLMCut, iSmearingSS ? "On":"Off",iWidthSSsmear,iMean_SSsmear,iExtraIsoCuts?"On":"Off",bWhichToSmear));

    // #### Define analysis task
  AliAnalysisTaskEMCALPhotonIsolation* task = new AliAnalysisTaskEMCALPhotonIsolation("Analysis",bHisto);

  TString configFile("config_PhotonIsolation.C"); //Name of config file
//  if(gSystem->AccessPathName(configFile.Data())){ //Check for exsisting file and delete it
//    gSystem->Exec(Form("rm %s",configFile.Data()));
//  }

  if(configBasePath.IsNull()){ //Check if a specific config should be used and copy appropriate file
	configBasePath="$ALICE_PHYSICS/PWGGA/EMCALTasks/macros";
  	gSystem->Exec(Form("cp %s/%s .",configBasePath.Data(),configFile.Data()));
  }
  else if(configBasePath.Contains("alien:///")){
  	gSystem->Exec(Form("alien_cp %s/%s .",configBasePath.Data(),configFile.Data()));
  }
  else{
  	gSystem->Exec(Form("cp %s/%s .",configBasePath.Data(),configFile.Data()));
  }

  configBasePath=Form("%s/",gSystem->pwd());
  ifstream configIn; //Open config file for hash calculation
  configIn.open(configFile);
  TString configStr;
  configStr.ReadFile(configIn);
  TString configMD5 = configStr.MD5();
  configMD5.Resize(5); //Short hash value for usable extension
  TString configFileMD5 = configFile;
  TDatime time; //Get timestamp
  Int_t timeStamp = time.GetTime();
  configFileMD5.ReplaceAll(".C",Form("\_%s_%i.C",configMD5.Data(),timeStamp));

  if(gSystem->AccessPathName(configFileMD5.Data())){ //Add additional identifier if file exists
    gSystem->Exec(Form("mv %s %s",configFile.Data(),configFileMD5.Data()));
  }
  else{
      while(!gSystem->AccessPathName(configFileMD5.Data())){
        configFileMD5.ReplaceAll(".C","_1.C");
      }
    gSystem->Exec(Form("mv %s %s",configFile.Data(),configFileMD5.Data()));
  }

  TString configFilePath(configBasePath+"/"+configFileMD5);
  gROOT->LoadMacro(configFilePath.Data());
  printf("Path of config file: %s\n",configFilePath.Data());

    // #### Task preferences
  task->SetOutputFormat(iOutput);
  task->SetLCAnalysis(kFALSE);
  task->SetIsoConeRadius(iIsoConeRadius);
  task->SetEtIsoThreshold(EtIso); // after should be replace by EtIso
  task->SetCTMdeltaEta(TMdeta); // after should be replaced by TMdeta
  task->SetCTMdeltaPhi(TMdphi); // after should be replaced by TMdphi
  task->SetQA(isQA);
  task->SetIsoMethod(iIsoMethod);
  task->SetEtIsoMethod(iEtIsoMethod);
  task->SetUEMethod(iUEMethod);
  task->SetUSEofTPC(bUseofTPC);
  task->SetMC(bIsMC);
  task->SetM02Smearing(iSmearingSS);
  task->SetWidth4Smear(iWidthSSsmear);
  task->SetMean4Smear(iMean_SSsmear);
  task->SetExtraIsoCuts(iExtraIsoCuts);
  task->SetAnalysispPb(i_pPb);
  task->SetNLMCut(bNLMCut,NLMCut,minNLM);
  task->SetPtBinning(ptBin);
  task->SetM02Binning(M02Bin);
  task->SetEtisoBinning(EtisoBin);
  task->SetEtueBinning(EtueBin);
  task->SetEtaBinning(EtaBin);
  task->SetPhiBinning(PhiBin);
  task->SetLabelBinning(LabelBin);
  task->SetPDGBinning(PDGBin);
  task->SetMomPDGBinning(MomPDGBin);
  task->SetClustPDGBinning(ClustPDGBin);
  task->SetDxBinning(DxBin);
  task->SetDzBinning(DzBin);
  task->SetDecayBinning(DecayBin);
  task->SetSmearForClusters(bWhichToSmear);

  if(bIsMC && bMCNormalization) task->SetIsPythia(kTRUE);

  TString name(Form("PhotonIsolation_%s_%s", ntracks, nclusters));
  cout<<"name of the containers  "<<name.Data()<<endl;

    // tracks to be used for the track matching (already used in TM task, TPC only tracks)
  AliTrackContainer *trackCont  = task->AddTrackContainer("tracks");
  if(!trackCont)
    Printf("Error with TPCOnly!!");
  trackCont->SetName("tpconlyMatch");
  trackCont->SetTrackFilterType(AliEmcalTrackSelection::kTPCOnlyTracks);
    // clusters to be used in the analysis already filtered
  AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters);

    // tracks to be used in the analysis (Hybrid tracks)
  AliTrackContainer * tracksForAnalysis = task->AddTrackContainer("tracks");
  if(!tracksForAnalysis)
    Printf("Error with Hybrids!!");
  tracksForAnalysis->SetName("filterTracksAna");
  tracksForAnalysis->SetFilterHybridTracks(kTRUE);
  if(!bIsMC){
    tracksForAnalysis->SetTrackCutsPeriod(periodstr);
  tracksForAnalysis->SetDefTrackCutsPeriod(periodstr);
  }
  Printf("Name of Tracks for matching: %s \n Name for Tracks for Isolation: %s",trackCont->GetName(),tracksForAnalysis->GetName());

  printf("Task for neutral cluster analysis created and configured, pass it to AnalysisManager\n");
    // #### Add analysis task
  manager->AddTask(task);

  AliAnalysisDataContainer *contHistos = manager->CreateContainer(myContName.Data(), TList::Class(), AliAnalysisManager::kOutputContainer,Form("%s:NeutralClusters",AliAnalysisManager::GetCommonFileName()));
  AliAnalysisDataContainer *cinput  = manager->GetCommonInputContainer();
  manager->ConnectInput(task, 0, cinput);
  manager->ConnectOutput(task, 1, contHistos);

  return task;
}
<commit_msg>Loading Geometry via the AliAnalysisTaskEmcal method (note that one should use the CDBConnect task first<commit_after>  ///////////////////////////////////////////////////////////////////////////
  ///\file AddTaskEMCALPhotonIsolation.C
  ///\brief Configuration of AliAnalysisTaskEMCALPhotonIsolation
  ///
  /// Version to be used in lego train for testing on pp@7TeV
  ///
  /// \author Lucile Ronflette <lucile.ronflette@cern.ch>, SUBATECH, Nantes
  /// \author Davide Francesco Lodato <davide.francesco.lodato@cern.ch>, Utrecht University
  /// \author Marco Marquard <marco.marquard@cern.ch>, University Frankfurt am Main
  ///////////////////////////////////////////////////////////////////////////

AliAnalysisTaskEMCALPhotonIsolation* AddTaskEMCALPhotonIsolation(
                                                                 const char*            periodstr                 = "LHC11c",
                                                                 const char*            ntracks                   = "EmcalTracks",
                                                                 const char*            nclusters                 = "EmcCaloClusters",
                                                                 const UInt_t           pSel                      = AliVEvent::kEMC7,
                                                                 const TString          dType                     = "ESD",
                                                                 const Bool_t	        bHisto                    = kTRUE,
                                                                 const Int_t	        iOutput	  	          = 0,
                                                                 const Bool_t	        bIsMC  	                  = kFALSE,
                                                                 const Bool_t           bMCNormalization          = kFALSE,
                                                                 const Bool_t           bNLMCut                   = kFALSE,
                                                                 const Int_t            NLMCut                    = 0,
                                                                 const Double_t         minPtCutCluster           = 0.3,
                                                                 const Double_t         EtIso                     = 2.,
                                                                 const Int_t            iIsoMethod                = 1,
                                                                 const Int_t            iEtIsoMethod              = 0,
                                                                 const Int_t            iUEMethod                 = 1,
                                                                 const Bool_t           bUseofTPC                 = kFALSE,
                                                                 const Double_t         TMdeta                    = 0.02,
                                                                 const Double_t         TMdphi                    = 0.03,
                                                                 const Bool_t           bTMClusterRejection       = kTRUE,
                                                                 const Bool_t           bTMClusterRejectionInCone = kTRUE,
                                                                 const Float_t          iIsoConeRadius            = 0.4,
                                                                 const Bool_t           iSmearingSS               = kFALSE,
                                                                 const Float_t          iWidthSSsmear             = 0.,
                                                                 const Float_t          iMean_SSsmear             = 0.,
                                                                 const Bool_t           iExtraIsoCuts             = kFALSE,
                                                                 const Bool_t           i_pPb                     = kFALSE,
                                                                 const Bool_t           isQA                      = kFALSE,
                                                                 TString                configBasePath            = "",
                                                                 const Int_t            bWhichToSmear             = 0,
                                                                 const Int_t            minNLM                    = 1
                                                                 )
{

  Printf("Preparing neutral cluster analysis\n");

    // #### Define manager and data container names
  AliAnalysisManager *manager = AliAnalysisManager::GetAnalysisManager();
  if (!manager) {
    ::Error("AddTaskEMCALPhotonIsolation", "No analysis manager to connect to.");
    return NULL;
  }

  printf("Creating container names for cluster analysis\n");
  TString myContName("");
  if(bIsMC)
    myContName = Form("Analysis_Neutrals_MC");
  else
    myContName = Form("Analysis_Neutrals");

  myContName.Append(Form("_TM_%s_CPVe%.2lf_CPVp%.2lf_IsoMet%d_EtIsoMet%d_UEMet%d_TPCbound_%s_IsoConeR%.1f_NLMCut_%s_minNLM%d_maxNLM%d_SSsmear_%s_Width%.3f_Mean_%.3f_PureIso_%s_WhichSmear_%d",bTMClusterRejection? "On" :"Off", TMdeta , TMdphi ,iIsoMethod,iEtIsoMethod,iUEMethod,bUseofTPC ? "Yes" : "No",iIsoConeRadius,bNLMCut ? "On": "Off",minNLM, NLMCut, iSmearingSS ? "On":"Off",iWidthSSsmear,iMean_SSsmear,iExtraIsoCuts?"On":"Off",bWhichToSmear));

    // #### Define analysis task
  AliAnalysisTaskEMCALPhotonIsolation* task = new AliAnalysisTaskEMCALPhotonIsolation("Analysis",bHisto);

  TString configFile("config_PhotonIsolation.C"); //Name of config file
//  if(gSystem->AccessPathName(configFile.Data())){ //Check for exsisting file and delete it
//    gSystem->Exec(Form("rm %s",configFile.Data()));
//  }

  if(configBasePath.IsNull()){ //Check if a specific config should be used and copy appropriate file
	configBasePath="$ALICE_PHYSICS/PWGGA/EMCALTasks/macros";
  	gSystem->Exec(Form("cp %s/%s .",configBasePath.Data(),configFile.Data()));
  }
  else if(configBasePath.Contains("alien:///")){
  	gSystem->Exec(Form("alien_cp %s/%s .",configBasePath.Data(),configFile.Data()));
  }
  else{
  	gSystem->Exec(Form("cp %s/%s .",configBasePath.Data(),configFile.Data()));
  }

  configBasePath=Form("%s/",gSystem->pwd());
  ifstream configIn; //Open config file for hash calculation
  configIn.open(configFile);
  TString configStr;
  configStr.ReadFile(configIn);
  TString configMD5 = configStr.MD5();
  configMD5.Resize(5); //Short hash value for usable extension
  TString configFileMD5 = configFile;
  TDatime time; //Get timestamp
  Int_t timeStamp = time.GetTime();
  configFileMD5.ReplaceAll(".C",Form("\_%s_%i.C",configMD5.Data(),timeStamp));

  if(gSystem->AccessPathName(configFileMD5.Data())){ //Add additional identifier if file exists
    gSystem->Exec(Form("mv %s %s",configFile.Data(),configFileMD5.Data()));
  }
  else{
      while(!gSystem->AccessPathName(configFileMD5.Data())){
        configFileMD5.ReplaceAll(".C","_1.C");
      }
    gSystem->Exec(Form("mv %s %s",configFile.Data(),configFileMD5.Data()));
  }

  TString configFilePath(configBasePath+"/"+configFileMD5);
  gROOT->LoadMacro(configFilePath.Data());
  printf("Path of config file: %s\n",configFilePath.Data());

    // #### Task preferences
  task->SetOutputFormat(iOutput);
  task->SetLCAnalysis(kFALSE);
  task->SetIsoConeRadius(iIsoConeRadius);
  task->SetEtIsoThreshold(EtIso); // after should be replace by EtIso
  task->SetCTMdeltaEta(TMdeta); // after should be replaced by TMdeta
  task->SetCTMdeltaPhi(TMdphi); // after should be replaced by TMdphi
  task->SetQA(isQA);
  task->SetIsoMethod(iIsoMethod);
  task->SetEtIsoMethod(iEtIsoMethod);
  task->SetUEMethod(iUEMethod);
  task->SetUSEofTPC(bUseofTPC);
  task->SetMC(bIsMC);
  task->SetM02Smearing(iSmearingSS);
  task->SetWidth4Smear(iWidthSSsmear);
  task->SetMean4Smear(iMean_SSsmear);
  task->SetExtraIsoCuts(iExtraIsoCuts);
  task->SetAnalysispPb(i_pPb);
  task->SetNLMCut(bNLMCut,NLMCut,minNLM);
  task->SetPtBinning(ptBin);
  task->SetM02Binning(M02Bin);
  task->SetEtisoBinning(EtisoBin);
  task->SetEtueBinning(EtueBin);
  task->SetEtaBinning(EtaBin);
  task->SetPhiBinning(PhiBin);
  task->SetLabelBinning(LabelBin);
  task->SetPDGBinning(PDGBin);
  task->SetMomPDGBinning(MomPDGBin);
  task->SetClustPDGBinning(ClustPDGBin);
  task->SetDxBinning(DxBin);
  task->SetDzBinning(DzBin);
  task->SetDecayBinning(DecayBin);
  task->SetSmearForClusters(bWhichToSmear);
  task->SetNeedEmcalGeom(kTRUE);

  if(bIsMC && bMCNormalization) task->SetIsPythia(kTRUE);

  TString name(Form("PhotonIsolation_%s_%s", ntracks, nclusters));
  cout<<"name of the containers  "<<name.Data()<<endl;

    // tracks to be used for the track matching (already used in TM task, TPC only tracks)
  AliTrackContainer *trackCont  = task->AddTrackContainer("tracks");
  if(!trackCont)
    Printf("Error with TPCOnly!!");
  trackCont->SetName("tpconlyMatch");
  trackCont->SetTrackFilterType(AliEmcalTrackSelection::kTPCOnlyTracks);
    // clusters to be used in the analysis already filtered
  AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters);

    // tracks to be used in the analysis (Hybrid tracks)
  AliTrackContainer * tracksForAnalysis = task->AddTrackContainer("tracks");
  if(!tracksForAnalysis)
    Printf("Error with Hybrids!!");
  tracksForAnalysis->SetName("filterTracksAna");
  tracksForAnalysis->SetFilterHybridTracks(kTRUE);
  if(!bIsMC){
    tracksForAnalysis->SetTrackCutsPeriod(periodstr);
  tracksForAnalysis->SetDefTrackCutsPeriod(periodstr);
  }
  Printf("Name of Tracks for matching: %s \n Name for Tracks for Isolation: %s",trackCont->GetName(),tracksForAnalysis->GetName());

  printf("Task for neutral cluster analysis created and configured, pass it to AnalysisManager\n");
    // #### Add analysis task
  manager->AddTask(task);

  AliAnalysisDataContainer *contHistos = manager->CreateContainer(myContName.Data(), TList::Class(), AliAnalysisManager::kOutputContainer,Form("%s:NeutralClusters",AliAnalysisManager::GetCommonFileName()));
  AliAnalysisDataContainer *cinput  = manager->GetCommonInputContainer();
  manager->ConnectInput(task, 0, cinput);
  manager->ConnectOutput(task, 1, contHistos);

  return task;
}
<|endoftext|>


<commit_before>AliAnalysisTaskHFEFlow* ConfigHFE_FLOW_TOFTPC(Bool_t useMC, Int_t tpcCls, Double_t tpcClsr,Int_t tpcClspid, Double_t tpcsharedfraction, Int_t itsCls, Double_t chi2peritscl, Int_t pixellayer, Double_t dcaxy, Double_t dcaz,  Double_t tofsig, Double_t tpcdedx0, Double_t tpcdedx1, Double_t tpcdedx2, Double_t tpcdedx3, Double_t tpcdedx4, Int_t vzero, Int_t debuglevel)
{
  //
  // HFE flow task
  //
  printf("Summary settings flow task\n");
  printf("TPC number of tracking clusters %d\n",tpcCls);
  printf("TPC ratio clusters %f\n",tpcClsr*0.01);
  printf("TPC number of pid clusters %d\n",tpcClspid);
  printf("Maximal fraction of TPC shared cluster %f\n",tpcsharedfraction*0.01);
  printf("ITS number of clusters %d\n",itsCls);
  printf("Maximal chi2 per ITS cluster %f\n",chi2peritscl);
  printf("Requirement on the pixel layer %d\n",pixellayer);
  printf("dcaxy %f\n",dcaxy*0.01);
  printf("dcaz %f\n",dcaz*0.01);
  printf("TOF sigma %f\n",tofsig*0.1);
  printf("TPC min sigma cut 0: %f\n",tpcdedx0*0.01);
  printf("TPC min sigma cut 1: %f\n",tpcdedx1*0.01);
  printf("TPC min sigma cut 2: %f\n",tpcdedx2*0.01);
  printf("TPC min sigma cut 3: %f\n",tpcdedx3*0.01);
  printf("TPC min sigma cut 4: %f\n",tpcdedx4*0.01);
  printf("VZERO event plane %d\n",vzero);
  printf("Debug level %d\n",debuglevel);

  // Cut HFE
  AliHFEcuts *hfecuts = new AliHFEcuts("hfeCuts","HFE Standard Cuts");
  hfecuts->CreateStandardCuts();
  hfecuts->SetMinNClustersTPC(tpcCls);
  hfecuts->SetMinNClustersTPCPID(tpcClspid);
  hfecuts->SetMinRatioTPCclusters(tpcClsr*0.01);
  hfecuts->SetTPCmodes(AliHFEextraCuts::kFound, AliHFEextraCuts::kFoundOverFindable);
  hfecuts->SetFractionOfSharedTPCClusters(tpcsharedfraction*0.01);

  hfecuts->SetMinNClustersITS(itsCls);
  hfecuts->SetCutITSpixel(pixellayer);
  hfecuts->SetCheckITSLayerStatus(kFALSE);

  hfecuts->SetMaxImpactParam(dcaxy*0.01,dcaz*0.01);

  //hfecuts->UnsetVertexRequirement();
  hfecuts->SetVertexRange(10.);

  hfecuts->SetTOFPIDStep(kTRUE);

  // Name
  TString appendix(TString::Format("TPC%dTPCr%dTPCpid%dTPCShared%dITScl%dChi2perITS%dPixelLayer%dDCAr%dz%dTOFsig%dTPCmindedx0%dTPCmindedx1%dTPCmindedx2%dTPCmindedx3%dTPCmindedx4%dVZERO%dDebugLevel%decorr%d",tpcCls,(Int_t)tpcClsr,tpcClspid,(Int_t) tpcsharedfraction,itsCls,(Int_t) chi2peritscl,(Int_t) pixellayer,(Int_t)dcaxy,(Int_t)dcaz,(Int_t)tofsig,(Int_t)tpcdedx0,(Int_t)tpcdedx1,(Int_t)tpcdedx2,(Int_t)tpcdedx3,(Int_t)tpcdedx4,vzero,debuglevel,(Int_t)withetacorrection));
  printf("appendix %s\n", appendix.Data());

  // The task
  AliAnalysisTaskHFEFlow *task = new AliAnalysisTaskHFEFlow(Form("HFEFlowtask_%s", appendix.Data()));
  task->SelectCollisionCandidates(AliVEvent::kMB | AliVEvent::kCentral | AliVEvent::kSemiCentral);
  task->SetDebugLevel(1);
  task->GetPIDQAManager()->SetHighResolutionHistos();
  task->SetHFECuts(hfecuts);
  if(useMC) {
    task->SetMCPID(kTRUE);
    //task->SetUseMCReactionPlane(kTRUE);
    task->SetAfterBurnerOn(kTRUE);
    task->SetV1V2V3V4V5(0.0,0.2,0.0,0.0,0.0);
  }
  if(vzero>=1) task->SetVZEROEventPlane(kTRUE);
  if(vzero==2) task->SetVZEROEventPlaneA(kTRUE);
  if(vzero==3) task->SetVZEROEventPlaneC(kTRUE);
  task->SetDebugLevel(debuglevel);

  // Define PID
  AliHFEpid *pid = task->GetPID();
  if(useMC) pid->SetHasMCData(kTRUE);
  pid->AddDetector("TOF", 0);
  pid->AddDetector("TPC", 1);

  TString datatype=gSystem->Getenv("CONFIG_FILE");

  if(!useMC) {

    Double_t params_centr_0_5[1];
    Double_t params_centr_5_10[1];
    Double_t params_centr_10_20[1];
    Double_t params_centr_20_30[1];
    Double_t params_centr_per[1];
    params_centr_0_5[0]=tpcdedx0*0.01;  // cut tuned for 0-10%
    params_centr_5_10[0]=tpcdedx1*0.01; // cut tuned for 0-10%
    params_centr_10_20[0]=tpcdedx2*0.01;
    params_centr_20_30[0]=tpcdedx3*0.01;
    params_centr_per[0]=tpcdedx4*0.01;

    char *cutmodel;
    cutmodel="pol0";

    for(Int_t a=0;a<11;a++)
      {
	if(a>3)  pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_per,3.0);
	if(a==0) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_0_5,3.0);    //  0-5%
	if(a==1) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_5_10,3.0);    //  5-10%
	if(a==2) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_10_20,3.0);    //  10-20%
	if(a==3) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_20_30,3.0);    //  20-30%
      }

  }

  pid->ConfigureTOF(tofsig*0.1);

  printf("*************************************\n");
  printf("Configuring standard Task:\n");
  task->Print();
  pid->PrintStatus();
  printf("*************************************\n");
  return task;

}
<commit_msg>Fix of the config<commit_after>AliAnalysisTaskHFEFlow* ConfigHFE_FLOW_TOFTPC(Bool_t useMC, Int_t tpcCls, Double_t tpcClsr,Int_t tpcClspid, Double_t tpcsharedfraction, Int_t itsCls, Double_t chi2peritscl, Int_t pixellayer, Double_t dcaxy, Double_t dcaz,  Double_t tofsig, Double_t tpcdedx0, Double_t tpcdedx1, Double_t tpcdedx2, Double_t tpcdedx3, Double_t tpcdedx4, Int_t vzero, Int_t debuglevel)
{
  //
  // HFE flow task
  //
  printf("Summary settings flow task\n");
  printf("TPC number of tracking clusters %d\n",tpcCls);
  printf("TPC ratio clusters %f\n",tpcClsr*0.01);
  printf("TPC number of pid clusters %d\n",tpcClspid);
  printf("Maximal fraction of TPC shared cluster %f\n",tpcsharedfraction*0.01);
  printf("ITS number of clusters %d\n",itsCls);
  printf("Maximal chi2 per ITS cluster %f\n",chi2peritscl);
  printf("Requirement on the pixel layer %d\n",pixellayer);
  printf("dcaxy %f\n",dcaxy*0.01);
  printf("dcaz %f\n",dcaz*0.01);
  printf("TOF sigma %f\n",tofsig*0.1);
  printf("TPC min sigma cut 0: %f\n",tpcdedx0*0.01);
  printf("TPC min sigma cut 1: %f\n",tpcdedx1*0.01);
  printf("TPC min sigma cut 2: %f\n",tpcdedx2*0.01);
  printf("TPC min sigma cut 3: %f\n",tpcdedx3*0.01);
  printf("TPC min sigma cut 4: %f\n",tpcdedx4*0.01);
  printf("VZERO event plane %d\n",vzero);
  printf("Debug level %d\n",debuglevel);

  // Cut HFE
  AliHFEcuts *hfecuts = new AliHFEcuts("hfeCuts","HFE Standard Cuts");
  hfecuts->CreateStandardCuts();
  hfecuts->SetMinNClustersTPC(tpcCls);
  hfecuts->SetMinNClustersTPCPID(tpcClspid);
  hfecuts->SetMinRatioTPCclusters(tpcClsr*0.01);
  hfecuts->SetTPCmodes(AliHFEextraCuts::kFound, AliHFEextraCuts::kFoundOverFindable);
  hfecuts->SetFractionOfSharedTPCClusters(tpcsharedfraction*0.01);

  hfecuts->SetMinNClustersITS(itsCls);
  hfecuts->SetCutITSpixel(pixellayer);
  hfecuts->SetCheckITSLayerStatus(kFALSE);

  hfecuts->SetMaxImpactParam(dcaxy*0.01,dcaz*0.01);

  //hfecuts->UnsetVertexRequirement();
  hfecuts->SetVertexRange(10.);

  hfecuts->SetTOFPIDStep(kTRUE);

  // Name
  TString appendix(TString::Format("TPC%dTPCr%dTPCpid%dTPCShared%dITScl%dChi2perITS%dPixelLayer%dDCAr%dz%dTOFsig%dTPCmindedx0%dTPCmindedx1%dTPCmindedx2%dTPCmindedx3%dTPCmindedx4%dVZERO%dDebugLevel%d",tpcCls,(Int_t)tpcClsr,tpcClspid,(Int_t) tpcsharedfraction,itsCls,(Int_t) chi2peritscl,(Int_t) pixellayer,(Int_t)dcaxy,(Int_t)dcaz,(Int_t)tofsig,(Int_t)tpcdedx0,(Int_t)tpcdedx1,(Int_t)tpcdedx2,(Int_t)tpcdedx3,(Int_t)tpcdedx4,vzero,debuglevel));
  printf("appendix %s\n", appendix.Data());

  // The task
  AliAnalysisTaskHFEFlow *task = new AliAnalysisTaskHFEFlow(Form("HFEFlowtask_%s", appendix.Data()));
  task->SelectCollisionCandidates(AliVEvent::kMB | AliVEvent::kCentral | AliVEvent::kSemiCentral);
  task->SetDebugLevel(1);
  task->GetPIDQAManager()->SetHighResolutionHistos();
  task->SetHFECuts(hfecuts);
  if(useMC) {
    task->SetMCPID(kTRUE);
    //task->SetUseMCReactionPlane(kTRUE);
    task->SetAfterBurnerOn(kTRUE);
    task->SetV1V2V3V4V5(0.0,0.2,0.0,0.0,0.0);
  }
  if(vzero>=1) task->SetVZEROEventPlane(kTRUE);
  if(vzero==2) task->SetVZEROEventPlaneA(kTRUE);
  if(vzero==3) task->SetVZEROEventPlaneC(kTRUE);
  task->SetDebugLevel(debuglevel);

  // Define PID
  AliHFEpid *pid = task->GetPID();
  if(useMC) pid->SetHasMCData(kTRUE);
  pid->AddDetector("TOF", 0);
  pid->AddDetector("TPC", 1);

  TString datatype=gSystem->Getenv("CONFIG_FILE");

  if(!useMC) {

    Double_t params_centr_0_5[1];
    Double_t params_centr_5_10[1];
    Double_t params_centr_10_20[1];
    Double_t params_centr_20_30[1];
    Double_t params_centr_per[1];
    params_centr_0_5[0]=tpcdedx0*0.01;  // cut tuned for 0-10%
    params_centr_5_10[0]=tpcdedx1*0.01; // cut tuned for 0-10%
    params_centr_10_20[0]=tpcdedx2*0.01;
    params_centr_20_30[0]=tpcdedx3*0.01;
    params_centr_per[0]=tpcdedx4*0.01;

    char *cutmodel;
    cutmodel="pol0";

    for(Int_t a=0;a<11;a++)
      {
	if(a>3)  pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_per,3.0);
	if(a==0) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_0_5,3.0);    //  0-5%
	if(a==1) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_5_10,3.0);    //  5-10%
	if(a==2) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_10_20,3.0);    //  10-20%
	if(a==3) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_20_30,3.0);    //  20-30%
      }

  }

  pid->ConfigureTOF(tofsig*0.1);

  printf("*************************************\n");
  printf("Configuring standard Task:\n");
  task->Print();
  pid->PrintStatus();
  printf("*************************************\n");
  return task;

}
<|endoftext|>


<commit_before>/*
 * This source file is part of libRocket, the HTML/CSS Interface Middleware
 *
 * For the latest information, see http://www.librocket.com
 *
 * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
 *
 * 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.
 *
 */
#pragma once

#include "LibRocketEventManagerSystem.h"
#include <Rocket/Core/Context.h>
#include <Rocket/Core/ElementDocument.h>
#include <Rocket/Core/ElementUtilities.h>
#include "EventHandler.h"
#include "EventInstancer.h"
#include <map>
#include <Globals.h>
#include <ToString.h>
#include <DebugUtil.h>
#include "libRocketBackendSystem.h"
#include "ClientConnectToServerSystem.h"
#include "GameState.h"
#include <TcpClient.h>
#include <Packet.h>
#include "PacketType.h"
#include "ClientStateSystem.h"
#include "ChangeStatePacket.h"
#include "SoundComponent.h"
#include "DisconnectPacket.h"
#include "ClientPacketHandlerSystem.h"

LibRocketEventManagerSystem::LibRocketEventManagerSystem(TcpClient* p_client)
	: EntitySystem(SystemType::LibRocketEventManagerSystem, 1, ComponentType::GameState)
{
	m_context = NULL;
	wantsToExit = false;
	m_eventHandler = NULL;
	m_currentDocId = "";
	m_client = p_client;
}

LibRocketEventManagerSystem::~LibRocketEventManagerSystem()
{
	shutdown();
}

void LibRocketEventManagerSystem::initialize()
{
	m_stateSystem = static_cast<ClientStateSystem*>(m_world->getSystem(
		SystemType::ClientStateSystem));
	auto rocketBackend = static_cast<LibRocketBackendSystem*>(
		m_world->getSystem(SystemType::LibRocketBackendSystem));

	m_context = rocketBackend->getContext();

	EventInstancer* eventInstancer = new EventInstancer(this);
	Rocket::Core::Factory::RegisterEventListenerInstancer(eventInstancer);
	eventInstancer->RemoveReference();

	m_menuEntity = m_world->createEntity();
	SoundComponent* soundComp = new SoundComponent();
	AudioHeader* header = new AudioHeader(AudioHeader::AMBIENT,"MenuOk");
	header->file = "Mine_Blip_v2.wav";
	header->volume = 0.3f;
	header->path = TESTSOUNDEFFECTPATH;
	soundComp->addAudioHeader(header);

	m_menuEntity->addComponent(soundComp);
	m_world->addEntity(m_menuEntity);
}

// Releases all event handlers registered with the manager.
void LibRocketEventManagerSystem::shutdown()
{
	m_eventHandlers.clear();
	m_eventHandler = NULL;
}

void LibRocketEventManagerSystem::registerEventHandler( EventHandler* p_handler )
{
	registerEventHandler(p_handler->getName().c_str(), p_handler);
}

// Registers a new event handler with the manager.
void LibRocketEventManagerSystem::registerEventHandler(const Rocket::Core::String&
													   p_handlerName,
													   EventHandler* p_handler)
{
	p_handler->connectToManager(this);
	// Release any handler bound under the same name.
	EventHandlerMap::iterator iterator = m_eventHandlers.find(p_handlerName);
	if (iterator != m_eventHandlers.end())
	{	//delete (*iterator).second;
		DEBUGWARNING(((
			toString("LibRocketEventManagerSystem::registerEventHandler\nAttempting to register EventHandler[")
			+ toString(p_handlerName.CString())
			+ toString("] which has already been registred in the EventManager.")).c_str()));
	}
	m_eventHandlers[p_handlerName] = p_handler;
}

EventHandler* LibRocketEventManagerSystem::unregisterEventHandler(
	const Rocket::Core::String& p_handlerName )
{
	EventHandlerMap::iterator iterator = m_eventHandlers.find(p_handlerName);
	EventHandler* handler = NULL;
	if (iterator != m_eventHandlers.end())
	{
		handler = (*iterator).second;
		handler->connectToManager(NULL);
		m_eventHandlers[p_handlerName] = NULL;
	}
	return handler;
}

void LibRocketEventManagerSystem::clearDocumentStack()
{
	while (!m_docIdStack.empty())
	{
		auto document = m_context->GetDocument(m_docIdStack.top());
		m_docIdStack.pop();
		if (document->IsVisible())
		{
			document->Show(Rocket::Core::ElementDocument::NONE);
			document->Hide();
		}
	}

	m_currentDocId = "";
}

// Processes an event coming through from Rocket.
void LibRocketEventManagerSystem::processEvent(Rocket::Core::Event& p_event,
											   const Rocket::Core::String& p_value)
{
	Rocket::Core::StringList commands;
	Rocket::Core::StringUtilities::ExpandString(commands, p_value, ';');
	for (size_t i = 0; i < commands.size(); ++i)
	{
		// Check for a generic 'load', 'exit' or 'modal' command.
		Rocket::Core::StringList values;
		Rocket::Core::StringUtilities::ExpandString(values, commands[i], ' ');

		if (values.empty())
			return;

		auto ownerDocument = p_event.GetTargetElement()->GetOwnerDocument();
		if (values[0] == "modal")
		{
		//	if (!ownerDocument->IsModal() && m_currentDocId == ownerDocument->GetId())
		//		ownerDocument->Show(Rocket::Core::ElementDocument::MODAL);
		}
		else if (values[0] == "goto" && values.size() > 1)
		{
			playConfirmSound();
			// Clear the stack from windows that are on top of the triggering one.
			clearStackUntilFoundDocId(ownerDocument->GetId());
			// If goto previous is specified, then hide this window, and open the
			// previous one saved on the stack
			if (values[1] == "previous")
			{
				// Pop current document id from the stack.
				m_docIdStack.pop();
				// Top and pop next document id. On loadWindow, it will be added again.
				// That's not pretty/efficient, but it isn't a problem either. // Alex
				Rocket::Core::String window = m_docIdStack.top();
				m_docIdStack.pop();
				if (loadWindow(window))
					ownerDocument->Hide();
			}
			// Load the window, and if successful hide the old window.
			else if (loadWindow(values[1]))
			{
				ownerDocument->Hide();
			}
		}
		else if (values[0] == "open" &&	values.size() > 1)
		{
			playConfirmSound();
			// Opens a window and pushes it to the stack, without hiding the parent window.
			// Clear other open windows on top.
			clearStackUntilFoundDocId(ownerDocument->GetId());
			loadWindow(values[1]);
			ownerDocument->Show(Rocket::Core::ElementDocument::NONE);
		}
		else if (values[0] == "clearStack"){
			clearDocumentStack();
		}
		else if (values[0] == "exit")
		{
			wantsToExit = true;
		}
		else if (values[0] == "connectToServer")
		{
			// "server_host" is the name attribute specified in the input element in the rml file.
			// "localhost" simply is provided as a default value, if the host isn't set. This could be left as "" as well.
			string server_address = p_event.GetParameter<Rocket::Core::String>
				("server_host", "localhost").CString();
			string server_port = p_event.GetParameter<Rocket::Core::String>
				("server_port", "1337").CString();
			string playerName = p_event.GetParameter<Rocket::Core::String>
				("player_name", "NotFound").CString();

			m_client->setPlayerName(playerName);
			auto sys = static_cast<ClientConnectToServerSystem*>(
				m_world->getSystem(SystemType::ClientConnectoToServerSystem));

			sys->setAddressAndConnect(server_address, server_port);
		}
		else if(values[0] == "start_game")
		{
			ChangeStatePacket letsRollPacket;
			letsRollPacket.m_gameState = GameStates::INITGAME;
			m_client->sendPacket(letsRollPacket.pack());
		}
		else if(values[0] == "host_server"){
			m_world->requestToHostServer();

			string server_port = p_event.GetParameter<Rocket::Core::String>
				("server_port", "1337").CString();

			string playerName = p_event.GetParameter<Rocket::Core::String>
				("player_name", "NotFound").CString();
			m_client->setPlayerName(playerName);

			auto sys = static_cast<ClientConnectToServerSystem*>(
				m_world->getSystem(SystemType::ClientConnectoToServerSystem));

			sys->setAddressAndConnect("127.0.0.1", server_port);
		}
		else if(values[0] == "leave_server"){
			DisconnectPacket dcPacket;
			dcPacket.playerID = m_client->getPlayerID();
			dcPacket.clientNetworkIdentity = m_client->getId();
			m_client->sendPacket(dcPacket.pack());
		}
		else if (values[0] == "reset_connection")
		{
			auto sys = static_cast<ClientPacketHandlerSystem*>(
				m_world->getSystem(SystemType::ClientPacketHandlerSystem));
			sys->resetFromDisconnect();
		}

		else if(values[0] == "play_confirm"){
			playConfirmSound();
		}
	}
}

void LibRocketEventManagerSystem::processEntities( const vector<Entity*>& p_entities )
{
	if (wantsToExit){
		m_world->requestToShutDown();
	}
}

void LibRocketEventManagerSystem::playConfirmSound()
{
	auto soundComp = static_cast<SoundComponent*>
		(m_menuEntity->getComponent(ComponentType::SoundComponent));

	soundComp->getSoundHeaderByName(AudioHeader::AMBIENT,"MenuOk")->
		queuedPlayingState = AudioHeader::PLAY;
}

void LibRocketEventManagerSystem::playBackSound()
{

}

// Loads a window and binds the event handler for it.
bool LibRocketEventManagerSystem::loadWindow(const Rocket::Core::String& p_windowName)
{
	// Set the event handler for the new screen, if one has been registered.
	EventHandler* old_event_handler = m_eventHandler;
	EventHandlerMap::iterator iterator = m_eventHandlers.find(p_windowName);
	if (iterator != m_eventHandlers.end())
		m_eventHandler = (*iterator).second;
	else
		m_eventHandler = NULL;

	auto document = m_context->GetDocument(p_windowName);
	if (document == NULL)
	{
		DEBUGWARNING(((
			toString("LibRocketEventManagerSystem::loadWindow\nNo document with the body id\"")
			+ toString(p_windowName.CString())
			+ toString("\" has been loaded.")).c_str()));
		m_eventHandler = old_event_handler;
		return false;
	}

	// Add this document to the stack!
	m_currentDocId = p_windowName;
	m_docIdStack.push(p_windowName);

	document->Show();
	document->PullToFront();

	// Remove the caller's reference.
	//document->RemoveReference();
	return true;
}

void LibRocketEventManagerSystem::clearStackUntilFoundDocId( const Rocket::Core::String&  p_docId )
{
	if(m_docIdStack.size()){
		while (m_docIdStack.top() != p_docId)
		{
			auto document = m_context->GetDocument(m_docIdStack.top());
			m_docIdStack.pop();
			if (document->IsVisible())
			{
				document->Show(Rocket::Core::ElementDocument::NONE);
				document->Hide();
			}
		}
	}
}<commit_msg>Dicsonnect popup should now vanish when pressing the button!<commit_after>/*
 * This source file is part of libRocket, the HTML/CSS Interface Middleware
 *
 * For the latest information, see http://www.librocket.com
 *
 * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
 *
 * 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.
 *
 */
#pragma once

#include "LibRocketEventManagerSystem.h"
#include <Rocket/Core/Context.h>
#include <Rocket/Core/ElementDocument.h>
#include <Rocket/Core/ElementUtilities.h>
#include "EventHandler.h"
#include "EventInstancer.h"
#include <map>
#include <Globals.h>
#include <ToString.h>
#include <DebugUtil.h>
#include "libRocketBackendSystem.h"
#include "ClientConnectToServerSystem.h"
#include "GameState.h"
#include <TcpClient.h>
#include <Packet.h>
#include "PacketType.h"
#include "ClientStateSystem.h"
#include "ChangeStatePacket.h"
#include "SoundComponent.h"
#include "DisconnectPacket.h"
#include "ClientPacketHandlerSystem.h"

LibRocketEventManagerSystem::LibRocketEventManagerSystem(TcpClient* p_client)
	: EntitySystem(SystemType::LibRocketEventManagerSystem, 1, ComponentType::GameState)
{
	m_context = NULL;
	wantsToExit = false;
	m_eventHandler = NULL;
	m_currentDocId = "";
	m_client = p_client;
}

LibRocketEventManagerSystem::~LibRocketEventManagerSystem()
{
	shutdown();
}

void LibRocketEventManagerSystem::initialize()
{
	m_stateSystem = static_cast<ClientStateSystem*>(m_world->getSystem(
		SystemType::ClientStateSystem));
	auto rocketBackend = static_cast<LibRocketBackendSystem*>(
		m_world->getSystem(SystemType::LibRocketBackendSystem));

	m_context = rocketBackend->getContext();

	EventInstancer* eventInstancer = new EventInstancer(this);
	Rocket::Core::Factory::RegisterEventListenerInstancer(eventInstancer);
	eventInstancer->RemoveReference();

	m_menuEntity = m_world->createEntity();
	SoundComponent* soundComp = new SoundComponent();
	AudioHeader* header = new AudioHeader(AudioHeader::AMBIENT,"MenuOk");
	header->file = "Mine_Blip_v2.wav";
	header->volume = 0.3f;
	header->path = TESTSOUNDEFFECTPATH;
	soundComp->addAudioHeader(header);

	m_menuEntity->addComponent(soundComp);
	m_world->addEntity(m_menuEntity);
}

// Releases all event handlers registered with the manager.
void LibRocketEventManagerSystem::shutdown()
{
	m_eventHandlers.clear();
	m_eventHandler = NULL;
}

void LibRocketEventManagerSystem::registerEventHandler( EventHandler* p_handler )
{
	registerEventHandler(p_handler->getName().c_str(), p_handler);
}

// Registers a new event handler with the manager.
void LibRocketEventManagerSystem::registerEventHandler(const Rocket::Core::String&
													   p_handlerName,
													   EventHandler* p_handler)
{
	p_handler->connectToManager(this);
	// Release any handler bound under the same name.
	EventHandlerMap::iterator iterator = m_eventHandlers.find(p_handlerName);
	if (iterator != m_eventHandlers.end())
	{	//delete (*iterator).second;
		DEBUGWARNING(((
			toString("LibRocketEventManagerSystem::registerEventHandler\nAttempting to register EventHandler[")
			+ toString(p_handlerName.CString())
			+ toString("] which has already been registred in the EventManager.")).c_str()));
	}
	m_eventHandlers[p_handlerName] = p_handler;
}

EventHandler* LibRocketEventManagerSystem::unregisterEventHandler(
	const Rocket::Core::String& p_handlerName )
{
	EventHandlerMap::iterator iterator = m_eventHandlers.find(p_handlerName);
	EventHandler* handler = NULL;
	if (iterator != m_eventHandlers.end())
	{
		handler = (*iterator).second;
		handler->connectToManager(NULL);
		m_eventHandlers[p_handlerName] = NULL;
	}
	return handler;
}

void LibRocketEventManagerSystem::clearDocumentStack()
{
	while (!m_docIdStack.empty())
	{
		auto document = m_context->GetDocument(m_docIdStack.top());
		m_docIdStack.pop();
		if (document->IsVisible())
		{
			document->Show(Rocket::Core::ElementDocument::NONE);
			document->Hide();
		}
	}

	m_currentDocId = "";
}

// Processes an event coming through from Rocket.
void LibRocketEventManagerSystem::processEvent(Rocket::Core::Event& p_event,
											   const Rocket::Core::String& p_value)
{
	Rocket::Core::StringList commands;
	Rocket::Core::StringUtilities::ExpandString(commands, p_value, ';');
	for (size_t i = 0; i < commands.size(); ++i)
	{
		// Check for a generic 'load', 'exit' or 'modal' command.
		Rocket::Core::StringList values;
		Rocket::Core::StringUtilities::ExpandString(values, commands[i], ' ');

		if (values.empty())
			return;

		auto ownerDocument = p_event.GetTargetElement()->GetOwnerDocument();
		if (values[0] == "modal")
		{
		//	if (!ownerDocument->IsModal() && m_currentDocId == ownerDocument->GetId())
		//		ownerDocument->Show(Rocket::Core::ElementDocument::MODAL);
		}
		else if (values[0] == "goto" && values.size() > 1)
		{
			playConfirmSound();
			// Clear the stack from windows that are on top of the triggering one.
			clearStackUntilFoundDocId(ownerDocument->GetId());
			// If goto previous is specified, then hide this window, and open the
			// previous one saved on the stack
			if (values[1] == "previous")
			{
				// Pop current document id from the stack.
				m_docIdStack.pop();
				// Top and pop next document id. On loadWindow, it will be added again.
				// That's not pretty/efficient, but it isn't a problem either. // Alex
				Rocket::Core::String window = m_docIdStack.top();
				m_docIdStack.pop();
				if (loadWindow(window))
					ownerDocument->Hide();
			}
			// Load the window, and if successful hide the old window.
			else if (loadWindow(values[1]))
			{
				ownerDocument->Hide();
			}
		}
		else if (values[0] == "open" &&	values.size() > 1)
		{
			playConfirmSound();
			// Opens a window and pushes it to the stack, without hiding the parent window.
			// Clear other open windows on top.
			clearStackUntilFoundDocId(ownerDocument->GetId());
			loadWindow(values[1]);
			ownerDocument->Show(Rocket::Core::ElementDocument::NONE);
		}
		else if (values[0] == "clearStack"){
			clearDocumentStack();
		}
		else if (values[0] == "exit")
		{
			wantsToExit = true;
		}
		else if (values[0] == "connectToServer")
		{
			// "server_host" is the name attribute specified in the input element in the rml file.
			// "localhost" simply is provided as a default value, if the host isn't set. This could be left as "" as well.
			string server_address = p_event.GetParameter<Rocket::Core::String>
				("server_host", "localhost").CString();
			string server_port = p_event.GetParameter<Rocket::Core::String>
				("server_port", "1337").CString();
			string playerName = p_event.GetParameter<Rocket::Core::String>
				("player_name", "NotFound").CString();

			m_client->setPlayerName(playerName);
			auto sys = static_cast<ClientConnectToServerSystem*>(
				m_world->getSystem(SystemType::ClientConnectoToServerSystem));

			sys->setAddressAndConnect(server_address, server_port);
		}
		else if(values[0] == "start_game")
		{
			ChangeStatePacket letsRollPacket;
			letsRollPacket.m_gameState = GameStates::INITGAME;
			m_client->sendPacket(letsRollPacket.pack());
		}
		else if(values[0] == "host_server"){
			m_world->requestToHostServer();

			string server_port = p_event.GetParameter<Rocket::Core::String>
				("server_port", "1337").CString();

			string playerName = p_event.GetParameter<Rocket::Core::String>
				("player_name", "NotFound").CString();
			m_client->setPlayerName(playerName);

			auto sys = static_cast<ClientConnectToServerSystem*>(
				m_world->getSystem(SystemType::ClientConnectoToServerSystem));

			sys->setAddressAndConnect("127.0.0.1", server_port);
		}
		else if(values[0] == "leave_server"){
			DisconnectPacket dcPacket;
			dcPacket.playerID = m_client->getPlayerID();
			dcPacket.clientNetworkIdentity = m_client->getId();
			m_client->sendPacket(dcPacket.pack());
		}
		else if (values[0] == "reset_connection")
		{
			ownerDocument->Show(Rocket::Core::ElementDocument::MODAL);
			ownerDocument->Hide();
			auto sys = static_cast<ClientPacketHandlerSystem*>(
				m_world->getSystem(SystemType::ClientPacketHandlerSystem));
			sys->resetFromDisconnect();
		}

		else if(values[0] == "play_confirm"){
			playConfirmSound();
		}
	}
}

void LibRocketEventManagerSystem::processEntities( const vector<Entity*>& p_entities )
{
	if (wantsToExit){
		m_world->requestToShutDown();
	}
}

void LibRocketEventManagerSystem::playConfirmSound()
{
	auto soundComp = static_cast<SoundComponent*>
		(m_menuEntity->getComponent(ComponentType::SoundComponent));

	soundComp->getSoundHeaderByName(AudioHeader::AMBIENT,"MenuOk")->
		queuedPlayingState = AudioHeader::PLAY;
}

void LibRocketEventManagerSystem::playBackSound()
{

}

// Loads a window and binds the event handler for it.
bool LibRocketEventManagerSystem::loadWindow(const Rocket::Core::String& p_windowName)
{
	// Set the event handler for the new screen, if one has been registered.
	EventHandler* old_event_handler = m_eventHandler;
	EventHandlerMap::iterator iterator = m_eventHandlers.find(p_windowName);
	if (iterator != m_eventHandlers.end())
		m_eventHandler = (*iterator).second;
	else
		m_eventHandler = NULL;

	auto document = m_context->GetDocument(p_windowName);
	if (document == NULL)
	{
		DEBUGWARNING(((
			toString("LibRocketEventManagerSystem::loadWindow\nNo document with the body id\"")
			+ toString(p_windowName.CString())
			+ toString("\" has been loaded.")).c_str()));
		m_eventHandler = old_event_handler;
		return false;
	}

	// Add this document to the stack!
	m_currentDocId = p_windowName;
	m_docIdStack.push(p_windowName);

	document->Show();
	document->PullToFront();

	// Remove the caller's reference.
	//document->RemoveReference();
	return true;
}

void LibRocketEventManagerSystem::clearStackUntilFoundDocId( const Rocket::Core::String&  p_docId )
{
	if(m_docIdStack.size()){
		while (m_docIdStack.top() != p_docId)
		{
			auto document = m_context->GetDocument(m_docIdStack.top());
			m_docIdStack.pop();
			if (document->IsVisible())
			{
				document->Show(Rocket::Core::ElementDocument::NONE);
				document->Hide();
			}
		}
	}
}<|endoftext|>


<commit_before>/******************************************************************************

  nomlib - C++11 cross-platform game engine

Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

******************************************************************************/
#include "nomlib/system/InputMapper/InputStateMapper.hpp"

namespace nom {

InputStateMapper::InputStateMapper( void )
{
  // NOM_LOG_TRACE( NOM );
}

InputStateMapper::~InputStateMapper( void )
{
  // NOM_LOG_TRACE( NOM );
}

bool InputStateMapper::active( const std::string& key ) const
{
  InputStateMap::const_iterator itr = this->states_.find( key );

  // No match found; do nothing.
  if( itr == this->states_.end() )
  {
    NOM_LOG_ERR( NOM, "Could not check for active state on the specified key: " + key );
    return false;
  }
  else
  {
    return itr->second.active;
  }
}

bool InputStateMapper::insert( const std::string& key, const InputActionMapper& map, bool active )
{
  InputActionState input_state;
  input_state.active = active;
  input_state.actions = map.get();

  InputStateMapper::Pair p( key, input_state );

  auto it = this->states_.insert( p );

  // No dice; the insertion failed for some reason!
  if( it.second == false )
  {
    NOM_LOG_ERR( NOM, "Could not insert state key: " + key );
    return false;
  }

  return true;
}

bool InputStateMapper::erase( const std::string& key )
{
  InputStateMap::const_iterator itr = this->states_.find( key );

  // No match found; do nothing.
  if( itr == this->states_.end() )
  {
    NOM_LOG_ERR( NOM, "Could not remove specified state key: " + key );
    return false;
  }
  else // Match found; remove the context mapping
  {
    this->states_.erase( itr );
    return true;
  }

  return false;
}

bool InputStateMapper::activate( const std::string& key )
{
  InputStateMap::iterator itr = this->states_.find( key );

  // No match found; do nothing.
  if( itr == this->states_.end() )
  {
    NOM_LOG_ERR( NOM, "Could not activate specified state key: " + key );
    return false;
  }
  else // Match found; set the input mapping as the active context.
  {
    itr->second.active = true;

    return true;
  }

  return false;
}

bool InputStateMapper::disable( const std::string& key )
{
  InputStateMap::iterator itr = this->states_.find( key );

  // No match found; do nothing.
  if( itr == this->states_.end() )
  {
    NOM_LOG_ERR( NOM, "Could not disable specified state key: " + key );
    return false;
  }
  else // Match found; disable the requested state
  {
    itr->second.active = false;
    return true;
  }

  return false;
}

void InputStateMapper::disable( void )
{
  for( auto itr = this->states_.begin(); itr != this->states_.end(); ++itr )
  {
    itr->second.active = false;
  }
}

bool InputStateMapper::activate_only( const std::string& key )
{
  // First, we need to make sure that the requested state even exists before we
  // flag anything inactive.
  InputStateMap::iterator it = this->states_.find( key );

  if( it == this->states_.end() )
  {
    NOM_LOG_ERR( NOM, "Could not find state key: " + key );
    return false;
  }

  // Iterate through all of our action-to-states and flag them inactive.
  for( InputStateMap::iterator itr = this->states_.begin(); itr != this->states_.end(); ++itr )
  {
    itr->second.active = false;
  }

  it = this->states_.find( key );

  // No match found; do nothing more!
  if( it == this->states_.end() )
  {
    NOM_LOG_ERR( NOM, "Could not activate only state key: " + key );
    return false;
  }
  else // Match found; enable the requested state
  {
    it->second.active = true;
    return true;
  }

  return false;
}

void InputStateMapper::clear( void )
{
  this->states_.clear();
}

void InputStateMapper::dump( void )
{
  for( auto itr = this->states_.begin(); itr != this->states_.end(); ++itr )
  {
    if( itr->second.active == true )
    {
      InputActionMapper::ActionMap& input_map = itr->second.actions;

      for( InputActionMapper::ActionMap::const_iterator itr = input_map.begin(); itr != input_map.end(); ++itr )
      {
        NOM_DUMP( itr->first );

        if ( itr->second != nullptr )
        {
          itr->second->dump();
        }
        else
        {
          NOM_LOG_ERR( NOM, "Invalid input mapping state." );
        }
      }
    }
  }
}

void InputStateMapper::on_event( const Event& ev )
{
  for( auto itr = this->states_.begin(); itr != this->states_.end(); ++itr )
  {
    if( itr->second.active == true )
    {
      InputActionMapper::ActionMap input_map = itr->second.actions;
      for( InputActionMapper::ActionMap::const_iterator itr = input_map.begin(); itr != input_map.end(); ++itr )
      {
        if( ev.type == SDL_KEYDOWN || ev.type == SDL_KEYUP )
        {
          if( this->on_key_press( *itr->second, ev ) )
          {
            itr->second->operator()( ev );
          }
        }
        else if( ev.type == SDL_MOUSEBUTTONDOWN || ev.type == SDL_MOUSEBUTTONUP )
        {
          if( this->on_mouse_button( *itr->second, ev ) )
          {
            itr->second->operator()( ev );
          }
        }
        else if( ev.type == SDL_MOUSEWHEEL || ev.type == SDL_MOUSEWHEEL )
        {
          if( this->on_mouse_wheel( *itr->second, ev ) )
          {
            itr->second->operator()( ev );
          }
        }
        else if( ev.type == SDL_JOYBUTTONDOWN || ev.type == SDL_JOYBUTTONUP )
        {
          if( this->on_joystick_button( *itr->second, ev ) )
          {
            itr->second->operator()( ev );
          }
        }
        else if( ev.type == SDL_JOYAXISMOTION )
        {
          if( this->on_joystick_axis( *itr->second, ev ) )
          {
            itr->second->operator()( ev );
          }
        }
      } // end input_map iteration
    } // end conditional active input state
  }
}

bool InputStateMapper::on_key_press( const InputAction& mapping, const Event& ev )
{
  Event evt = mapping.event();

  if( evt.type != ev.type ) return false;

  // Handle matching the set keyboard actions to the user's input
  if( evt.key.sym == ev.key.sym && evt.key.mod == ev.key.mod
                                &&
      evt.key.repeat == ev.key.repeat
    )
  {
    // Matched
    return true;
  }

  // No match to any mapped action
  return false;
}

bool InputStateMapper::on_mouse_button( const InputAction& mapping, const Event& ev )
{
  Event evt = mapping.event();

  if( evt.type != ev.type ) return false;

  // Successful match is a mouse click that matches both the button used
  // (left, middle, right, ...) and its number of clicks (single, double, ...)
  if( evt.mouse.clicks == ev.mouse.clicks && evt.mouse.button == ev.mouse.button )
  {
    // Match
    return true;
  }

  // No match; number of clicks mismatch
  return false;
}

bool InputStateMapper::on_mouse_wheel( const InputAction& mapping, const Event& ev )
{
  Event evt = mapping.event();

  // if( mapping.wheel == nullptr ) return false;

  if( evt.type != ev.type ) return false;

  // NOTE: X & Y coordinate values depend on the construction of a WheelAction
  // object.
  // if( evt.wheel.axis == MouseWheelAction::AXIS_X )
  if( evt.wheel.x != MouseWheelAction::null )
  {
    // Left
    if( evt.wheel.x >= MouseWheelAction::LEFT && ev.wheel.x >= MouseWheelAction::LEFT )
    {
      return true;
    }

    // Right
    if( evt.wheel.x <= MouseWheelAction::RIGHT && ev.wheel.x <= MouseWheelAction::RIGHT )
    {
      return true;
    }
  }
  // else if( evt.wheel.axis == MouseWheelAction::AXIS_Y )
  else if( evt.wheel.y != MouseWheelAction::null )
  {
    // Up
    if( evt.wheel.y >= MouseWheelAction::UP && ev.wheel.y >= MouseWheelAction::UP )
    {
      return true;
    }

    // Down
    if( evt.wheel.y <= MouseWheelAction::DOWN && ev.wheel.y <= MouseWheelAction::DOWN )
    {
      return true;
    }
  }

  // Initialized to an invalid state!
  NOM_ASSERT( evt.wheel.x == 0 || evt.wheel.y == 0 );

  return false;
}

bool InputStateMapper::on_joystick_button( const InputAction& mapping, const Event& ev )
{
  Event evt = mapping.event();

  // if( mapping.jbutton == nullptr ) return false;

  if( evt.type != ev.type ) return false;

  if( evt.jbutton.id != ev.jbutton.id ) return false;

  if( evt.jbutton.button == ev.jbutton.button ) return true;

  return false;
}

// FIXME: Implementation is incomplete!
bool InputStateMapper::on_joystick_axis( const InputAction& mapping, const Event& ev )
{
  Event evt = mapping.event();

  // if( mapping.jaxis == nullptr ) return false;

  if( evt.type != ev.type ) return false;

  if( evt.jaxis.id != ev.jaxis.id ) return false;

  if( evt.jaxis.axis != ev.jaxis.axis ) return false;

  // Within dead-zone tolerance
  if( ( ev.jaxis.value < -3200 ) || ( ev.jaxis.value > 3200 ) )
  {
    // Up-down axis (Sony PS3 game controller)
    if( evt.jaxis.axis == 0 )
    {
      // Up
      if( evt.jaxis.value < 0 ) return true;

      // Down
      if( evt.jaxis.value > 0 ) return true;
    }

    // Left-right axis (Sony PS3 game controller)
    if( evt.jaxis.axis == 1 )
    {
      // Left
      if( evt.jaxis.value < 0 ) return true;

      // Right
      if( evt.jaxis.value > 0 ) return true;
    }
  }

  return false;
}

} // namespace nom
<commit_msg>InputStateMapper: Ignore key repeat logic unless non-zero (explicit)<commit_after>/******************************************************************************

  nomlib - C++11 cross-platform game engine

Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

******************************************************************************/
#include "nomlib/system/InputMapper/InputStateMapper.hpp"

namespace nom {

InputStateMapper::InputStateMapper( void )
{
  // NOM_LOG_TRACE( NOM );
}

InputStateMapper::~InputStateMapper( void )
{
  // NOM_LOG_TRACE( NOM );
}

bool InputStateMapper::active( const std::string& key ) const
{
  InputStateMap::const_iterator itr = this->states_.find( key );

  // No match found; do nothing.
  if( itr == this->states_.end() )
  {
    NOM_LOG_ERR( NOM, "Could not check for active state on the specified key: " + key );
    return false;
  }
  else
  {
    return itr->second.active;
  }
}

bool InputStateMapper::insert( const std::string& key, const InputActionMapper& map, bool active )
{
  InputActionState input_state;
  input_state.active = active;
  input_state.actions = map.get();

  InputStateMapper::Pair p( key, input_state );

  auto it = this->states_.insert( p );

  // No dice; the insertion failed for some reason!
  if( it.second == false )
  {
    NOM_LOG_ERR( NOM, "Could not insert state key: " + key );
    return false;
  }

  return true;
}

bool InputStateMapper::erase( const std::string& key )
{
  InputStateMap::const_iterator itr = this->states_.find( key );

  // No match found; do nothing.
  if( itr == this->states_.end() )
  {
    NOM_LOG_ERR( NOM, "Could not remove specified state key: " + key );
    return false;
  }
  else // Match found; remove the context mapping
  {
    this->states_.erase( itr );
    return true;
  }

  return false;
}

bool InputStateMapper::activate( const std::string& key )
{
  InputStateMap::iterator itr = this->states_.find( key );

  // No match found; do nothing.
  if( itr == this->states_.end() )
  {
    NOM_LOG_ERR( NOM, "Could not activate specified state key: " + key );
    return false;
  }
  else // Match found; set the input mapping as the active context.
  {
    itr->second.active = true;

    return true;
  }

  return false;
}

bool InputStateMapper::disable( const std::string& key )
{
  InputStateMap::iterator itr = this->states_.find( key );

  // No match found; do nothing.
  if( itr == this->states_.end() )
  {
    NOM_LOG_ERR( NOM, "Could not disable specified state key: " + key );
    return false;
  }
  else // Match found; disable the requested state
  {
    itr->second.active = false;
    return true;
  }

  return false;
}

void InputStateMapper::disable( void )
{
  for( auto itr = this->states_.begin(); itr != this->states_.end(); ++itr )
  {
    itr->second.active = false;
  }
}

bool InputStateMapper::activate_only( const std::string& key )
{
  // First, we need to make sure that the requested state even exists before we
  // flag anything inactive.
  InputStateMap::iterator it = this->states_.find( key );

  if( it == this->states_.end() )
  {
    NOM_LOG_ERR( NOM, "Could not find state key: " + key );
    return false;
  }

  // Iterate through all of our action-to-states and flag them inactive.
  for( InputStateMap::iterator itr = this->states_.begin(); itr != this->states_.end(); ++itr )
  {
    itr->second.active = false;
  }

  it = this->states_.find( key );

  // No match found; do nothing more!
  if( it == this->states_.end() )
  {
    NOM_LOG_ERR( NOM, "Could not activate only state key: " + key );
    return false;
  }
  else // Match found; enable the requested state
  {
    it->second.active = true;
    return true;
  }

  return false;
}

void InputStateMapper::clear( void )
{
  this->states_.clear();
}

void InputStateMapper::dump( void )
{
  for( auto itr = this->states_.begin(); itr != this->states_.end(); ++itr )
  {
    if( itr->second.active == true )
    {
      InputActionMapper::ActionMap& input_map = itr->second.actions;

      for( InputActionMapper::ActionMap::const_iterator itr = input_map.begin(); itr != input_map.end(); ++itr )
      {
        NOM_DUMP( itr->first );

        if ( itr->second != nullptr )
        {
          itr->second->dump();
        }
        else
        {
          NOM_LOG_ERR( NOM, "Invalid input mapping state." );
        }
      }
    }
  }
}

void InputStateMapper::on_event( const Event& ev )
{
  for( auto itr = this->states_.begin(); itr != this->states_.end(); ++itr )
  {
    if( itr->second.active == true )
    {
      InputActionMapper::ActionMap input_map = itr->second.actions;
      for( InputActionMapper::ActionMap::const_iterator itr = input_map.begin(); itr != input_map.end(); ++itr )
      {
        if( ev.type == SDL_KEYDOWN || ev.type == SDL_KEYUP )
        {
          if( this->on_key_press( *itr->second, ev ) )
          {
            itr->second->operator()( ev );
          }
        }
        else if( ev.type == SDL_MOUSEBUTTONDOWN || ev.type == SDL_MOUSEBUTTONUP )
        {
          if( this->on_mouse_button( *itr->second, ev ) )
          {
            itr->second->operator()( ev );
          }
        }
        else if( ev.type == SDL_MOUSEWHEEL || ev.type == SDL_MOUSEWHEEL )
        {
          if( this->on_mouse_wheel( *itr->second, ev ) )
          {
            itr->second->operator()( ev );
          }
        }
        else if( ev.type == SDL_JOYBUTTONDOWN || ev.type == SDL_JOYBUTTONUP )
        {
          if( this->on_joystick_button( *itr->second, ev ) )
          {
            itr->second->operator()( ev );
          }
        }
        else if( ev.type == SDL_JOYAXISMOTION )
        {
          if( this->on_joystick_axis( *itr->second, ev ) )
          {
            itr->second->operator()( ev );
          }
        }
      } // end input_map iteration
    } // end conditional active input state
  }
}

bool InputStateMapper::on_key_press( const InputAction& mapping, const Event& ev )
{
  Event evt = mapping.event();

  if( evt.type != ev.type ) return false;

  // Handle a keyboard action with repeat; only trigger if the event is a
  // repeating one
  if( evt.key.repeat != 0 )
  {
    if( evt.key.sym == ev.key.sym && evt.key.mod == ev.key.mod &&
        evt.key.repeat == ev.key.repeat )
    {
      // Matched
      return true;
    }
  }
  else  // Handle normal keyboard action; repeating makes no difference to us
  {
    if( evt.key.sym == ev.key.sym && evt.key.mod == ev.key.mod ) {
      // Matched
      return true;
    }
  }

  // No match to any mapped action
  return false;
}

bool InputStateMapper::on_mouse_button( const InputAction& mapping, const Event& ev )
{
  Event evt = mapping.event();

  if( evt.type != ev.type ) return false;

  // Successful match is a mouse click that matches both the button used
  // (left, middle, right, ...) and its number of clicks (single, double, ...)
  if( evt.mouse.clicks == ev.mouse.clicks && evt.mouse.button == ev.mouse.button )
  {
    // Match
    return true;
  }

  // No match; number of clicks mismatch
  return false;
}

bool InputStateMapper::on_mouse_wheel( const InputAction& mapping, const Event& ev )
{
  Event evt = mapping.event();

  // if( mapping.wheel == nullptr ) return false;

  if( evt.type != ev.type ) return false;

  // NOTE: X & Y coordinate values depend on the construction of a WheelAction
  // object.
  // if( evt.wheel.axis == MouseWheelAction::AXIS_X )
  if( evt.wheel.x != MouseWheelAction::null )
  {
    // Left
    if( evt.wheel.x >= MouseWheelAction::LEFT && ev.wheel.x >= MouseWheelAction::LEFT )
    {
      return true;
    }

    // Right
    if( evt.wheel.x <= MouseWheelAction::RIGHT && ev.wheel.x <= MouseWheelAction::RIGHT )
    {
      return true;
    }
  }
  // else if( evt.wheel.axis == MouseWheelAction::AXIS_Y )
  else if( evt.wheel.y != MouseWheelAction::null )
  {
    // Up
    if( evt.wheel.y >= MouseWheelAction::UP && ev.wheel.y >= MouseWheelAction::UP )
    {
      return true;
    }

    // Down
    if( evt.wheel.y <= MouseWheelAction::DOWN && ev.wheel.y <= MouseWheelAction::DOWN )
    {
      return true;
    }
  }

  // Initialized to an invalid state!
  NOM_ASSERT( evt.wheel.x == 0 || evt.wheel.y == 0 );

  return false;
}

bool InputStateMapper::on_joystick_button( const InputAction& mapping, const Event& ev )
{
  Event evt = mapping.event();

  // if( mapping.jbutton == nullptr ) return false;

  if( evt.type != ev.type ) return false;

  if( evt.jbutton.id != ev.jbutton.id ) return false;

  if( evt.jbutton.button == ev.jbutton.button ) return true;

  return false;
}

// FIXME: Implementation is incomplete!
bool InputStateMapper::on_joystick_axis( const InputAction& mapping, const Event& ev )
{
  Event evt = mapping.event();

  // if( mapping.jaxis == nullptr ) return false;

  if( evt.type != ev.type ) return false;

  if( evt.jaxis.id != ev.jaxis.id ) return false;

  if( evt.jaxis.axis != ev.jaxis.axis ) return false;

  // Within dead-zone tolerance
  if( ( ev.jaxis.value < -3200 ) || ( ev.jaxis.value > 3200 ) )
  {
    // Up-down axis (Sony PS3 game controller)
    if( evt.jaxis.axis == 0 )
    {
      // Up
      if( evt.jaxis.value < 0 ) return true;

      // Down
      if( evt.jaxis.value > 0 ) return true;
    }

    // Left-right axis (Sony PS3 game controller)
    if( evt.jaxis.axis == 1 )
    {
      // Left
      if( evt.jaxis.value < 0 ) return true;

      // Right
      if( evt.jaxis.value > 0 ) return true;
    }
  }

  return false;
}

} // namespace nom
<|endoftext|>