<commit_before>void AddTask_LMeeCocktailMC(Int_t CollisionSystem = 200, Float_t MaxEta = 0.8, Float_t MinPt = 0.2, Bool_t WriteTTree = kFALSE, Int_t ResolType = 2 , Int_t ALTweightType = 1, TString resFileName = "") {

  // ================= Load Librariers =================================
  gSystem->Load("libCore");
  gSystem->Load("libTree");
  gSystem->Load("libGeom");
  gSystem->Load("libVMC");
  gSystem->Load("libPhysics");
  gSystem->Load("libMinuit");
  gSystem->Load("libSTEERBase");
  gSystem->Load("libESD");
  gSystem->Load("libAOD");
  gSystem->Load("libANALYSIS");
  gSystem->Load("libANALYSISalice");
  gSystem->Load("libCDB");
  gSystem->Load("libSTEER");
  gSystem->Load("libSTEERBase");
  gSystem->Load("libTender");
  gSystem->Load("libTenderSupplies");
  gSystem->Load("libPWGflowBase");
  gSystem->Load("libPWGflowTasks");
  gSystem->Load("libPWGGAGammaConv");

  // ================== GetAnalysisManager ===============================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTask_LMeeCocktailMC", "No analysis manager found.");
    return ;
  }

  // ================== GetInputEventHandler =============================
  AliVEventHandler *inputHandler=mgr->GetInputEventHandler();
  //            find input container
  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();

  //================================================
  //========= Add task to the ANALYSIS manager =====
  //================================================

  AliAnalysisTaskLMeeCocktailMC *task=NULL;
  task= new AliAnalysisTaskLMeeCocktailMC(Form("LMeeCocktailMC_%1.2f",MaxEta));
  task->SetCollisionSystem(CollisionSystem);
  task->SetMaxEta(MaxEta);
  task->SetMinPt(MinPt);
  task->SetWriteTTree(WriteTTree);
  task->SetResolType(ResolType);
  task->SetALTweight(ALTweightType);
	if(pPbDataSetName != ""){
		task->SetpPbResFileName(resFileName);
	}

  //connect containers
  AliAnalysisDataContainer *coutput =
  mgr->CreateContainer(Form("LMeeCocktailMC_%1.2f",MaxEta), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:LMeeCocktailMC",AliAnalysisManager::GetCommonFileName()));

  mgr->AddTask(task);
  mgr->ConnectInput(task,0,cinput);
  mgr->ConnectOutput(task,1,coutput);

  return;
}
<commit_msg>Variable name<commit_after>void AddTask_LMeeCocktailMC(Int_t CollisionSystem = 200, Float_t MaxEta = 0.8, Float_t MinPt = 0.2, Bool_t WriteTTree = kFALSE, Int_t ResolType = 2 , Int_t ALTweightType = 1, TString resFileName = "") {

  // ================= Load Librariers =================================
  gSystem->Load("libCore");
  gSystem->Load("libTree");
  gSystem->Load("libGeom");
  gSystem->Load("libVMC");
  gSystem->Load("libPhysics");
  gSystem->Load("libMinuit");
  gSystem->Load("libSTEERBase");
  gSystem->Load("libESD");
  gSystem->Load("libAOD");
  gSystem->Load("libANALYSIS");
  gSystem->Load("libANALYSISalice");
  gSystem->Load("libCDB");
  gSystem->Load("libSTEER");
  gSystem->Load("libSTEERBase");
  gSystem->Load("libTender");
  gSystem->Load("libTenderSupplies");
  gSystem->Load("libPWGflowBase");
  gSystem->Load("libPWGflowTasks");
  gSystem->Load("libPWGGAGammaConv");

  // ================== GetAnalysisManager ===============================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTask_LMeeCocktailMC", "No analysis manager found.");
    return ;
  }

  // ================== GetInputEventHandler =============================
  AliVEventHandler *inputHandler=mgr->GetInputEventHandler();
  //            find input container
  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();

  //================================================
  //========= Add task to the ANALYSIS manager =====
  //================================================

  AliAnalysisTaskLMeeCocktailMC *task=NULL;
  task= new AliAnalysisTaskLMeeCocktailMC(Form("LMeeCocktailMC_%1.2f",MaxEta));
  task->SetCollisionSystem(CollisionSystem);
  task->SetMaxEta(MaxEta);
  task->SetMinPt(MinPt);
  task->SetWriteTTree(WriteTTree);
  task->SetResolType(ResolType);
  task->SetALTweight(ALTweightType);
	if(resFileName != ""){
		task->SetpPbResFileName(resFileName);
	}

  //connect containers
  AliAnalysisDataContainer *coutput =
  mgr->CreateContainer(Form("LMeeCocktailMC_%1.2f",MaxEta), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:LMeeCocktailMC",AliAnalysisManager::GetCommonFileName()));

  mgr->AddTask(task);
  mgr->ConnectInput(task,0,cinput);
  mgr->ConnectOutput(task,1,coutput);

  return;
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: Friederike Bock, Lucia Leardini , A. Marin                     *
 * Version 1.0                                                            *
 *                                                                        *
 *                                                                        *
 * 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.                  *
 **************************************************************************/

//***************************************************************************************
//This AddTask is supposed to set up the main task
//($ALIPHYSICS/PWGGA/GammaConv/AliAnalysisTaskMaterialHistos.cxx) for
//pp together with all supporting classes
//***************************************************************************************

//***************************************************************************************
//CutHandler contains all cuts for a certain analysis and trainconfig,
//it automatically checks length of cutStrings and takes care of the number of added cuts,
//no specification of the variable 'numberOfCuts' needed anymore.
//***************************************************************************************

class CutHandlerConv{
  public:
    CutHandlerConv(Int_t nMax=10){
      nCuts=0; nMaxCuts=nMax; validCuts = true;
      eventCutArray = new TString[nMaxCuts]; photonCutArray = new TString[nMaxCuts]; mesonCutArray = new TString[nMaxCuts]; clusterCutArray = new TString[nMaxCuts];
      for(Int_t i=0; i<nMaxCuts; i++) {eventCutArray[i] = ""; photonCutArray[i] = ""; mesonCutArray[i] = ""; clusterCutArray[i] = "";}
    }
    void AddCut(TString eventCut, TString photonCut){
      if(nCuts>=nMaxCuts) {cout << "ERROR in CutHandlerConv: Exceeded maximum number of cuts!" << endl; validCuts = false; return;}
      if( eventCut.Length()!=8 || photonCut.Length()!=26  ) {cout << "ERROR in CutHandlerConv: Incorrect length of cut string!" << endl; validCuts = false; return;}
      eventCutArray[nCuts]=eventCut; photonCutArray[nCuts]=photonCut; mesonCutArray[nCuts]=""; clusterCutArray[nCuts]="";
      nCuts++;
      return;
    }
    void AddCut(TString eventCut, TString photonCut, TString mesonCut){
      if(nCuts>=nMaxCuts) {cout << "ERROR in CutHandlerConv: Exceeded maximum number of cuts!" << endl; validCuts = false; return;}
      if( eventCut.Length()!=8 || photonCut.Length()!=26 || mesonCut.Length()!=16 ) {cout << "ERROR in CutHandlerConv: Incorrect length of cut string!" << endl; validCuts = false; return;}
      eventCutArray[nCuts]=eventCut; photonCutArray[nCuts]=photonCut; mesonCutArray[nCuts]=mesonCut; clusterCutArray[nCuts]="";
      nCuts++;
      return;
    }
    void AddCut(TString eventCut, TString photonCut, TString mesonCut, TString clusterCut){
      if(nCuts>=nMaxCuts) {cout << "ERROR in CutHandlerConv: Exceeded maximum number of cuts!" << endl; validCuts = false; return;}
      if( eventCut.Length()!=8 || photonCut.Length()!=26 || mesonCut.Length()!=16 || clusterCut.Length()!=19 ) {cout << "ERROR in CutHandlerConv: Incorrect length of cut string!" << endl; validCuts = false; return;}
      eventCutArray[nCuts]=eventCut; photonCutArray[nCuts]=photonCut; mesonCutArray[nCuts]=mesonCut; clusterCutArray[nCuts]=clusterCut;
      nCuts++;
      return;
    }

    Bool_t AreValid(){return validCuts;}
    Int_t GetNCuts(){if(validCuts) return nCuts; else return 0;}
    TString GetEventCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return eventCutArray[i]; else{cout << "ERROR in CutHandlerConv: GetEventCut wrong index i" << endl;return "";}}
    TString GetPhotonCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return photonCutArray[i]; else {cout << "ERROR in CutHandlerConv: GetPhotonCut wrong index i" << endl;return "";}}
    TString GetMesonCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return mesonCutArray[i]; else {cout << "ERROR in CutHandlerConv: GetMesonCut wrong index i" << endl;return "";}}
    TString GetClusterCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return clusterCutArray[i]; else {cout << "ERROR in CutHandlerConv: GetClusterCut wrong index i" << endl;return "";}}
  private:
    Bool_t validCuts;
    Int_t nCuts; Int_t nMaxCuts;
    TString* eventCutArray;
    TString* photonCutArray;
    TString* mesonCutArray;
    TString* clusterCutArray;
};

void AddTask_MaterialHistos_PbPb(	Int_t   trainConfig                 = 1,                    // change different set of cuts
                Int_t 	isMC 				= 0,
				TString periodname                      = "LHC10b",           // period name
				TString periodNameV0Reader              = "",
				TString periodNameAnchor                = "",
				Bool_t 	enableV0findingEffi 		= kFALSE							// enables V0finding efficiency histograms
				){

  // ================= Load Librariers =================================
  gSystem->Load("libCore");
  gSystem->Load("libTree");
  gSystem->Load("libGeom");
  gSystem->Load("libVMC");
  gSystem->Load("libPhysics");
  gSystem->Load("libMinuit");
  gSystem->Load("libSTEERBase");
  gSystem->Load("libESD");
  gSystem->Load("libAOD");
  gSystem->Load("libANALYSIS");
  gSystem->Load("libANALYSISalice");
  gSystem->Load("libCDB");
  gSystem->Load("libSTEER");
  gSystem->Load("libSTEERBase");
  gSystem->Load("libTender");
  gSystem->Load("libTenderSupplies");
  gSystem->Load("libPWGflowBase");
  gSystem->Load("libPWGflowTasks");
  gSystem->Load("libPWGGAGammaConv");

  Int_t IsHeavyIon = 1;
  // ================== GetAnalysisManager ===============================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error(Form("AddTask_GammaConvV1_%i",trainConfig), "No analysis manager found.");
    return ;
  }

  // ================== GetInputEventHandler =============================
  AliVEventHandler *inputHandler=mgr->GetInputEventHandler();
  Bool_t isMCForOtherSettings = 0;
  if (isMC > 0) isMCForOtherSettings = 1;
  //========= Add PID Reponse to ANALYSIS manager ====
  if(!(AliPIDResponse*)mgr->GetTask("PIDResponseTask")){
    gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C");
    AddTaskPIDResponse(isMCForOtherSettings);
  }

  //=========  Set Cutnumber for V0Reader ================================
  TString cutnumberPhoton = "00000000000000000500000000";
  //00000070000000000500004000   V0 Reader cuts in GammaConv PbPb task
  TString cutnumberEvent = "10000103";
  //10000003
  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();

  Bool_t  enableConstructGamma=kFALSE;
  if (trainConfig>200){
    enableConstructGamma=kTRUE;
  }
  if (trainConfig>100 && trainConfig<200 ){
    cutnumberPhoton = "10000000000000000500000000";
  }

  //========= Add V0 Reader to  ANALYSIS manager if not yet existent =====
  TString V0ReaderName = Form("V0ReaderV1_%s_%s",cutnumberEvent.Data(),cutnumberPhoton.Data());
  if( !(AliV0ReaderV1*)mgr->GetTask(V0ReaderName.Data()) ){
    AliV0ReaderV1 *fV0ReaderV1 = new AliV0ReaderV1(V0ReaderName.Data());
    if (periodNameV0Reader.CompareTo("") != 0) fV0ReaderV1->SetPeriodName(periodNameV0Reader);
    fV0ReaderV1->SetUseOwnXYZCalculation(kTRUE);
    fV0ReaderV1->SetUseConstructGamma(enableConstructGamma);
    fV0ReaderV1->SetCreateAODs(kFALSE);// AOD Output
    fV0ReaderV1->SetUseAODConversionPhoton(kTRUE);
    fV0ReaderV1->SetProduceV0FindingEfficiency(enableV0findingEffi);
    if (!mgr) {
      Error("AddTask_V0ReaderV1", "No analysis manager found.");
      return;
    }

    AliConvEventCuts *fEventCuts=NULL;
    if(cutnumberEvent!=""){
      fEventCuts= new AliConvEventCuts(cutnumberEvent.Data(),cutnumberEvent.Data());
      fEventCuts->SetPreSelectionCutFlag(kTRUE);
      fEventCuts->SetV0ReaderName(V0ReaderName);
      if(fEventCuts->InitializeCutsFromCutString(cutnumberEvent.Data())){
        fV0ReaderV1->SetEventCuts(fEventCuts);
        fEventCuts->SetFillCutHistograms("",kTRUE);
      }
    }

    // Set AnalysisCut Number
    AliConversionPhotonCuts *fCuts=NULL;
    if(cutnumberPhoton!=""){
      fCuts= new AliConversionPhotonCuts(cutnumberPhoton.Data(),cutnumberPhoton.Data());
      fCuts->SetPreSelectionCutFlag(kTRUE);
      fCuts->SetIsHeavyIon(IsHeavyIon);
      fCuts->SetV0ReaderName(V0ReaderName);
      if(fCuts->InitializeCutsFromCutString(cutnumberPhoton.Data())){
        fV0ReaderV1->SetConversionCuts(fCuts);
        fCuts->SetFillCutHistograms("",kTRUE);
      }
    }

    if(inputHandler->IsA()==AliAODInputHandler::Class()){
      // AOD mode
      fV0ReaderV1->SetDeltaAODBranchName(Form("GammaConv_%s_gamma",cutnumberAODBranch.Data()));
    }
    fV0ReaderV1->Init();

    AliLog::SetGlobalLogLevel(AliLog::kInfo);

    //connect input V0Reader
    mgr->AddTask(fV0ReaderV1);
    mgr->ConnectInput(fV0ReaderV1,0,cinput);

  } else {
    Error("AddTask_V0ReaderV1", "Cannot execute AddTask, V0ReaderV1 already exists.");
  }

  //================================================
  //========= Add task to the ANALYSIS manager =====
  //            find input container

  AliAnalysisTaskMaterialHistos *fMaterialHistos=NULL;
  fMaterialHistos= new AliAnalysisTaskMaterialHistos(Form("MaterialHistos_%i",trainConfig));
  fMaterialHistos->SetIsMC(isMC);
  fMaterialHistos->SetIsHeavyIon(IsHeavyIon);
  fMaterialHistos->SetV0ReaderName(V0ReaderName);

  CutHandlerConv cuts;
  if(trainConfig == 1){
    cuts.AddCut("20010103", "00000009247602008250404000"); // INT7, CL1

    // Offline V0Finder is used

  } else  if(trainConfig == 101){
    cuts.AddCut("20010103", "10000009247602008250404000");  //INT7, CL1

  }else {
    Error(Form("GammaConvV1_%i",trainConfig), "wrong trainConfig variable no cuts have been specified for the configuration");
    return;
  }

	if(!cuts.AreValid()){
    cout << "\n\n****************************************************" << endl;
    cout << "ERROR: No valid cuts stored in CutHandlerConv! Returning..." << endl;
    cout << "****************************************************\n\n" << endl;
    return;
  }

  Int_t numberOfCuts = cuts.GetNCuts();

  TList *EventCutList = new TList();
  TList *ConvCutList = new TList();

  EventCutList->SetOwner(kTRUE);
  AliConvEventCuts **analysisEventCuts        = new AliConvEventCuts*[numberOfCuts];
  ConvCutList->SetOwner(kTRUE);
  AliConversionPhotonCuts **analysisCuts      = new AliConversionPhotonCuts*[numberOfCuts];
  for(Int_t i = 0; i<numberOfCuts; i++){
    analysisEventCuts[i]          = new AliConvEventCuts();
    analysisEventCuts[i]->InitializeCutsFromCutString((cuts.GetEventCut(i)).Data());
    analysisEventCuts[i]->SetV0ReaderName(V0ReaderName);
    EventCutList->Add(analysisEventCuts[i]);
    analysisEventCuts[i]->SetFillCutHistograms("",kTRUE);

    analysisCuts[i]               = new AliConversionPhotonCuts();
    analysisCuts[i]->InitializeCutsFromCutString((cuts.GetPhotonCut(i)).Data());
    analysisCuts[i]->SetV0ReaderName(V0ReaderName);
    ConvCutList->Add(analysisCuts[i]);
    analysisCuts[i]->SetFillCutHistograms("",kTRUE);

   }

  fMaterialHistos->SetEventCutList(numberOfCuts,EventCutList);
  fMaterialHistos->SetConversionCutList(numberOfCuts,ConvCutList);
  mgr->AddTask(fMaterialHistos);

  AliAnalysisDataContainer *coutput =
    mgr->CreateContainer(Form("GammaConvMaterial_%i",trainConfig), TList::Class(),
			 AliAnalysisManager::kOutputContainer,Form("GammaConv_Material_%i.root",trainConfig ));

  mgr->ConnectInput(fMaterialHistos,  0, cinput );
  mgr->ConnectOutput(fMaterialHistos,  1, coutput);
  //connect containers
	return;
}
<commit_msg>changed trainconfig material histos PbPb<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: Friederike Bock, Lucia Leardini , A. Marin                     *
 * Version 1.0                                                            *
 *                                                                        *
 *                                                                        *
 * 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.                  *
 **************************************************************************/

//***************************************************************************************
//This AddTask is supposed to set up the main task
//($ALIPHYSICS/PWGGA/GammaConv/AliAnalysisTaskMaterialHistos.cxx) for
//pp together with all supporting classes
//***************************************************************************************

//***************************************************************************************
//CutHandler contains all cuts for a certain analysis and trainconfig,
//it automatically checks length of cutStrings and takes care of the number of added cuts,
//no specification of the variable 'numberOfCuts' needed anymore.
//***************************************************************************************

class CutHandlerConv{
  public:
    CutHandlerConv(Int_t nMax=10){
      nCuts=0; nMaxCuts=nMax; validCuts = true;
      eventCutArray = new TString[nMaxCuts]; photonCutArray = new TString[nMaxCuts]; mesonCutArray = new TString[nMaxCuts]; clusterCutArray = new TString[nMaxCuts];
      for(Int_t i=0; i<nMaxCuts; i++) {eventCutArray[i] = ""; photonCutArray[i] = ""; mesonCutArray[i] = ""; clusterCutArray[i] = "";}
    }
    void AddCut(TString eventCut, TString photonCut){
      if(nCuts>=nMaxCuts) {cout << "ERROR in CutHandlerConv: Exceeded maximum number of cuts!" << endl; validCuts = false; return;}
      if( eventCut.Length()!=8 || photonCut.Length()!=26  ) {cout << "ERROR in CutHandlerConv: Incorrect length of cut string!" << endl; validCuts = false; return;}
      eventCutArray[nCuts]=eventCut; photonCutArray[nCuts]=photonCut; mesonCutArray[nCuts]=""; clusterCutArray[nCuts]="";
      nCuts++;
      return;
    }
    void AddCut(TString eventCut, TString photonCut, TString mesonCut){
      if(nCuts>=nMaxCuts) {cout << "ERROR in CutHandlerConv: Exceeded maximum number of cuts!" << endl; validCuts = false; return;}
      if( eventCut.Length()!=8 || photonCut.Length()!=26 || mesonCut.Length()!=16 ) {cout << "ERROR in CutHandlerConv: Incorrect length of cut string!" << endl; validCuts = false; return;}
      eventCutArray[nCuts]=eventCut; photonCutArray[nCuts]=photonCut; mesonCutArray[nCuts]=mesonCut; clusterCutArray[nCuts]="";
      nCuts++;
      return;
    }
    void AddCut(TString eventCut, TString photonCut, TString mesonCut, TString clusterCut){
      if(nCuts>=nMaxCuts) {cout << "ERROR in CutHandlerConv: Exceeded maximum number of cuts!" << endl; validCuts = false; return;}
      if( eventCut.Length()!=8 || photonCut.Length()!=26 || mesonCut.Length()!=16 || clusterCut.Length()!=19 ) {cout << "ERROR in CutHandlerConv: Incorrect length of cut string!" << endl; validCuts = false; return;}
      eventCutArray[nCuts]=eventCut; photonCutArray[nCuts]=photonCut; mesonCutArray[nCuts]=mesonCut; clusterCutArray[nCuts]=clusterCut;
      nCuts++;
      return;
    }

    Bool_t AreValid(){return validCuts;}
    Int_t GetNCuts(){if(validCuts) return nCuts; else return 0;}
    TString GetEventCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return eventCutArray[i]; else{cout << "ERROR in CutHandlerConv: GetEventCut wrong index i" << endl;return "";}}
    TString GetPhotonCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return photonCutArray[i]; else {cout << "ERROR in CutHandlerConv: GetPhotonCut wrong index i" << endl;return "";}}
    TString GetMesonCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return mesonCutArray[i]; else {cout << "ERROR in CutHandlerConv: GetMesonCut wrong index i" << endl;return "";}}
    TString GetClusterCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return clusterCutArray[i]; else {cout << "ERROR in CutHandlerConv: GetClusterCut wrong index i" << endl;return "";}}
  private:
    Bool_t validCuts;
    Int_t nCuts; Int_t nMaxCuts;
    TString* eventCutArray;
    TString* photonCutArray;
    TString* mesonCutArray;
    TString* clusterCutArray;
};

void AddTask_MaterialHistos_PbPb(	Int_t   trainConfig                 = 1,                    // change different set of cuts
                Int_t 	isMC 				= 0,
				TString periodname                      = "LHC10b",           // period name
				TString periodNameV0Reader              = "",
				TString periodNameAnchor                = "",
				Bool_t 	enableV0findingEffi 		= kFALSE							// enables V0finding efficiency histograms
				){

  // ================= Load Librariers =================================
  gSystem->Load("libCore");
  gSystem->Load("libTree");
  gSystem->Load("libGeom");
  gSystem->Load("libVMC");
  gSystem->Load("libPhysics");
  gSystem->Load("libMinuit");
  gSystem->Load("libSTEERBase");
  gSystem->Load("libESD");
  gSystem->Load("libAOD");
  gSystem->Load("libANALYSIS");
  gSystem->Load("libANALYSISalice");
  gSystem->Load("libCDB");
  gSystem->Load("libSTEER");
  gSystem->Load("libSTEERBase");
  gSystem->Load("libTender");
  gSystem->Load("libTenderSupplies");
  gSystem->Load("libPWGflowBase");
  gSystem->Load("libPWGflowTasks");
  gSystem->Load("libPWGGAGammaConv");

  Int_t IsHeavyIon = 1;
  // ================== GetAnalysisManager ===============================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error(Form("AddTask_GammaConvV1_%i",trainConfig), "No analysis manager found.");
    return ;
  }

  // ================== GetInputEventHandler =============================
  AliVEventHandler *inputHandler=mgr->GetInputEventHandler();
  Bool_t isMCForOtherSettings = 0;
  if (isMC > 0) isMCForOtherSettings = 1;
  //========= Add PID Reponse to ANALYSIS manager ====
  if(!(AliPIDResponse*)mgr->GetTask("PIDResponseTask")){
    gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C");
    AddTaskPIDResponse(isMCForOtherSettings);
  }

  //=========  Set Cutnumber for V0Reader ================================
  TString cutnumberPhoton = "00000000000000000500000000";
  TString cutnumberEvent = "10000003";
  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();

  Bool_t  enableConstructGamma=kFALSE;
  if (trainConfig>200){
    enableConstructGamma=kTRUE;
  }
  if (trainConfig>100 && trainConfig<200 ){
    cutnumberPhoton = "10000000000000000500000000";
  }

  //========= Add V0 Reader to  ANALYSIS manager if not yet existent =====
  TString V0ReaderName = Form("V0ReaderV1_%s_%s",cutnumberEvent.Data(),cutnumberPhoton.Data());
  if( !(AliV0ReaderV1*)mgr->GetTask(V0ReaderName.Data()) ){
    AliV0ReaderV1 *fV0ReaderV1 = new AliV0ReaderV1(V0ReaderName.Data());
    if (periodNameV0Reader.CompareTo("") != 0) fV0ReaderV1->SetPeriodName(periodNameV0Reader);
    fV0ReaderV1->SetUseOwnXYZCalculation(kTRUE);
    fV0ReaderV1->SetUseConstructGamma(enableConstructGamma);
    fV0ReaderV1->SetCreateAODs(kFALSE);// AOD Output
    fV0ReaderV1->SetUseAODConversionPhoton(kTRUE);
    fV0ReaderV1->SetProduceV0FindingEfficiency(enableV0findingEffi);
    if (!mgr) {
      Error("AddTask_V0ReaderV1", "No analysis manager found.");
      return;
    }

    AliConvEventCuts *fEventCuts=NULL;
    if(cutnumberEvent!=""){
      fEventCuts= new AliConvEventCuts(cutnumberEvent.Data(),cutnumberEvent.Data());
      fEventCuts->SetPreSelectionCutFlag(kTRUE);
      fEventCuts->SetV0ReaderName(V0ReaderName);
      if(fEventCuts->InitializeCutsFromCutString(cutnumberEvent.Data())){
        fV0ReaderV1->SetEventCuts(fEventCuts);
        fEventCuts->SetFillCutHistograms("",kTRUE);
      }
    }

    // Set AnalysisCut Number
    AliConversionPhotonCuts *fCuts=NULL;
    if(cutnumberPhoton!=""){
      fCuts= new AliConversionPhotonCuts(cutnumberPhoton.Data(),cutnumberPhoton.Data());
      fCuts->SetPreSelectionCutFlag(kTRUE);
      fCuts->SetIsHeavyIon(IsHeavyIon);
      fCuts->SetV0ReaderName(V0ReaderName);
      if(fCuts->InitializeCutsFromCutString(cutnumberPhoton.Data())){
        fV0ReaderV1->SetConversionCuts(fCuts);
        fCuts->SetFillCutHistograms("",kTRUE);
      }
    }

    if(inputHandler->IsA()==AliAODInputHandler::Class()){
      // AOD mode
      fV0ReaderV1->SetDeltaAODBranchName(Form("GammaConv_%s_gamma",cutnumberAODBranch.Data()));
    }
    fV0ReaderV1->Init();

    AliLog::SetGlobalLogLevel(AliLog::kInfo);

    //connect input V0Reader
    mgr->AddTask(fV0ReaderV1);
    mgr->ConnectInput(fV0ReaderV1,0,cinput);

  } else {
    Error("AddTask_V0ReaderV1", "Cannot execute AddTask, V0ReaderV1 already exists.");
  }

  //================================================
  //========= Add task to the ANALYSIS manager =====
  //            find input container

  AliAnalysisTaskMaterialHistos *fMaterialHistos=NULL;
  fMaterialHistos= new AliAnalysisTaskMaterialHistos(Form("MaterialHistos_%i",trainConfig));
  fMaterialHistos->SetIsMC(isMC);
  fMaterialHistos->SetIsHeavyIon(IsHeavyIon);
  fMaterialHistos->SetV0ReaderName(V0ReaderName);

  CutHandlerConv cuts;
   if(trainConfig == 1){
     cuts.AddCut("10000013", "00000009247602008250404000"); // kMB, V0M

    // Offline V0Finder is used

  } else  if(trainConfig == 101){
    cuts.AddCut("20010103", "10000009247602008250404000");  //INT7, CL1

  }else {
    Error(Form("GammaConvV1_%i",trainConfig), "wrong trainConfig variable no cuts have been specified for the configuration");
    return;
  }

	if(!cuts.AreValid()){
    cout << "\n\n****************************************************" << endl;
    cout << "ERROR: No valid cuts stored in CutHandlerConv! Returning..." << endl;
    cout << "****************************************************\n\n" << endl;
    return;
  }

  Int_t numberOfCuts = cuts.GetNCuts();

  TList *EventCutList = new TList();
  TList *ConvCutList = new TList();

  EventCutList->SetOwner(kTRUE);
  AliConvEventCuts **analysisEventCuts        = new AliConvEventCuts*[numberOfCuts];
  ConvCutList->SetOwner(kTRUE);
  AliConversionPhotonCuts **analysisCuts      = new AliConversionPhotonCuts*[numberOfCuts];
  for(Int_t i = 0; i<numberOfCuts; i++){
    analysisEventCuts[i]          = new AliConvEventCuts();
    analysisEventCuts[i]->InitializeCutsFromCutString((cuts.GetEventCut(i)).Data());
    analysisEventCuts[i]->SetV0ReaderName(V0ReaderName);
    EventCutList->Add(analysisEventCuts[i]);
    analysisEventCuts[i]->SetFillCutHistograms("",kTRUE);

    analysisCuts[i]               = new AliConversionPhotonCuts();
    analysisCuts[i]->InitializeCutsFromCutString((cuts.GetPhotonCut(i)).Data());
    analysisCuts[i]->SetV0ReaderName(V0ReaderName);
    ConvCutList->Add(analysisCuts[i]);
    analysisCuts[i]->SetFillCutHistograms("",kTRUE);

   }

  fMaterialHistos->SetEventCutList(numberOfCuts,EventCutList);
  fMaterialHistos->SetConversionCutList(numberOfCuts,ConvCutList);
  mgr->AddTask(fMaterialHistos);

  AliAnalysisDataContainer *coutput =
    mgr->CreateContainer(Form("GammaConvMaterial_%i",trainConfig), TList::Class(),
			 AliAnalysisManager::kOutputContainer,Form("GammaConv_Material_%i.root",trainConfig ));

  mgr->ConnectInput(fMaterialHistos,  0, cinput );
  mgr->ConnectOutput(fMaterialHistos,  1, coutput);
  //connect containers
	return;
}
<|endoftext|>


<commit_before>// EMCal tender task adder
// Author: Jiri Kral

AliTender *AddTaskEMCALTender(const char *geoname="EMCAL_COMPLETEV1", AliEMCALRecParam *pars = 0 )
{
  // Parameters: geoname = "EMCAL_FIRSTYEARV1" or "EMCAL_COMPLETEV1" or ""

  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskEMCALTender", "No analysis manager to connect to.");
    return NULL;
  }

  // Create the task and configure it.
  //===========================================================================
  AliTender* ana = new  AliTender("TenderTask");

  mgr->AddTask(ana);

  // Adding EMCAL supply
  AliEMCALTenderSupply *EMCALSupply=new AliEMCALTenderSupply("EMCALtender");

  EMCALSupply->SetEMCALGeometryName(geoname);

  // prepare the reco params ------------------------------------------------
	if( pars == 0 ){
		// you can write your reco params here to avoid loading them automatically
		// from OCDB during execution time
		AliEMCALRecParam *params = new AliEMCALRecParam();
		// reclustering parameters
		// use v1 for pp and v2 for PbPb
		params->SetClusterizerFlag(AliEMCALRecParam::kClusterizerv2);
		params->SetClusteringThreshold(0.1); // 100 MeV
		params->SetMinECut(0.05); //50 MeV
		params->SetW0(4.5);
		// you may want to enable the timing cut
		params->SetTimeCut(1e6);// s
		params->SetTimeMin(-1);
		params->SetTimeMax(1e6);//s

		EMCALSupply->SetRecParam(params);
	}
	else{
		cout << "------- TENDER is using supplied reco params -------" << endl;
		pars->Print( "reco" );
		cout << "----------------------------------------------------" << endl;
		EMCALSupply->SetRecParam(pars);
	}

  // prepare tender parameters ----------------------------------------------
  EMCALSupply->SetDebugLevel( 0 );

  // fiducial cut
  EMCALSupply->SetNumberOfCellsFromEMCALBorder( 1 );

  // nonlinearity
  EMCALSupply->SetNonLinearityFunction( AliEMCALTenderSupply::kBeamTestCorrected );

  // track matching parameters
  //EMCALSupply->SetMass(0.139);
  //EMCALSupply->SetStep(5);
  EMCALSupply->SwitchOnCutEtaPhiSum();
  EMCALSupply->SetRCut(0.025);
  //EMCALSupply->SwitchOnCutEtaPhiSeparate();
  EMCALSupply->SetEtaCut(0.025);
  EMCALSupply->SetPhiCut(0.05);

  // switches ---------------------------------------------------------------
  EMCALSupply->SwitchOnBadCellRemove();
  EMCALSupply->SwitchOnExoticCellRemove();
  EMCALSupply->SwitchOnCalibrateEnergy();
  EMCALSupply->SwitchOnCalibrateTime();
  EMCALSupply->SwitchOnUpdateCell();
  EMCALSupply->SwitchOnReclustering();
  EMCALSupply->SwitchOnClusterBadChannelCheck();
  EMCALSupply->SwitchOnClusterExoticChannelCheck();
  EMCALSupply->SwitchOnCellFiducialRegion();
  EMCALSupply->SwitchOnReCalibrateCluster();
  EMCALSupply->SwitchOnRecalculateClusPos();
  EMCALSupply->SwitchOnRecalShowerShape();
  EMCALSupply->SwitchOnRecalDistBadChannel();
  EMCALSupply->SwitchOnNonLinearityCorrection();
  EMCALSupply->SwitchOnTrackMatch();

  ana->AddSupply(EMCALSupply);
  // Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //==============================================================================
//  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("histosEmcalTender", TList::Class(),AliAnalysisManager::kOutputContainer,Form("%s", AliAnalysisManager::GetCommonFileName()));
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("emcal_tender_event", AliESDEvent::Class(),
                           AliAnalysisManager::kExchangeContainer,"emcal_tender");

  mgr->ConnectInput  (ana, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput (ana, 1, coutput1 );

  return ana;
}

<commit_msg>Switching off reclustering in tender supply for ET analysis<commit_after>// EMCal tender task adder
// Author: Jiri Kral

AliTender *AddTaskEMCALTender(const char *geoname="EMCAL_COMPLETEV1", AliEMCALRecParam *pars = 0 )
{
  // Parameters: geoname = "EMCAL_FIRSTYEARV1" or "EMCAL_COMPLETEV1" or ""

  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskEMCALTender", "No analysis manager to connect to.");
    return NULL;
  }

  // Create the task and configure it.
  //===========================================================================
  AliTender* ana = new  AliTender("TenderTask");

  mgr->AddTask(ana);

  // Adding EMCAL supply
  AliEMCALTenderSupply *EMCALSupply=new AliEMCALTenderSupply("EMCALtender");

  EMCALSupply->SetEMCALGeometryName(geoname);

  // prepare the reco params ------------------------------------------------
	if( pars == 0 ){
		// you can write your reco params here to avoid loading them automatically
		// from OCDB during execution time
		AliEMCALRecParam *params = new AliEMCALRecParam();
		// reclustering parameters
		// use v1 for pp and v2 for PbPb
		params->SetClusterizerFlag(AliEMCALRecParam::kClusterizerv2);
		params->SetClusteringThreshold(0.1); // 100 MeV
		params->SetMinECut(0.05); //50 MeV
		params->SetW0(4.5);
		// you may want to enable the timing cut
		params->SetTimeCut(1e6);// s
		params->SetTimeMin(-1);
		params->SetTimeMax(1e6);//s

		EMCALSupply->SetRecParam(params);
	}
	else{
		cout << "------- TENDER is using supplied reco params -------" << endl;
		pars->Print( "reco" );
		cout << "----------------------------------------------------" << endl;
		EMCALSupply->SetRecParam(pars);
	}

  // prepare tender parameters ----------------------------------------------
  EMCALSupply->SetDebugLevel( 0 );

  // fiducial cut
  EMCALSupply->SetNumberOfCellsFromEMCALBorder( 1 );

  // nonlinearity
  EMCALSupply->SetNonLinearityFunction( AliEMCALTenderSupply::kBeamTestCorrected );

  // track matching parameters
  //EMCALSupply->SetMass(0.139);
  //EMCALSupply->SetStep(5);
  EMCALSupply->SwitchOnCutEtaPhiSum();
  EMCALSupply->SetRCut(0.025);
  //EMCALSupply->SwitchOnCutEtaPhiSeparate();
  EMCALSupply->SetEtaCut(0.025);
  EMCALSupply->SetPhiCut(0.05);

  // switches ---------------------------------------------------------------
  EMCALSupply->SwitchOnBadCellRemove();
  EMCALSupply->SwitchOnExoticCellRemove();
  EMCALSupply->SwitchOnCalibrateEnergy();
  EMCALSupply->SwitchOnCalibrateTime();
  EMCALSupply->SwitchOnUpdateCell();
  //EMCALSupply->SwitchOnReclustering();
  EMCALSupply->SwitchOnClusterBadChannelCheck();
  EMCALSupply->SwitchOnClusterExoticChannelCheck();
  EMCALSupply->SwitchOnCellFiducialRegion();
  EMCALSupply->SwitchOnReCalibrateCluster();
  EMCALSupply->SwitchOnRecalculateClusPos();
  EMCALSupply->SwitchOnRecalShowerShape();
  EMCALSupply->SwitchOnRecalDistBadChannel();
  EMCALSupply->SwitchOnNonLinearityCorrection();
  EMCALSupply->SwitchOnTrackMatch();

  ana->AddSupply(EMCALSupply);
  // Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //==============================================================================
//  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("histosEmcalTender", TList::Class(),AliAnalysisManager::kOutputContainer,Form("%s", AliAnalysisManager::GetCommonFileName()));
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("emcal_tender_event", AliESDEvent::Class(),
                           AliAnalysisManager::kExchangeContainer,"emcal_tender");

  mgr->ConnectInput  (ana, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput (ana, 1, coutput1 );

  return ana;
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "platform/graphics/GraphicsContextRecorder.h"

#include "platform/graphics/ImageBuffer.h"
#include "platform/graphics/ImageSource.h"
#include "platform/graphics/LoggingCanvas.h"
#include "platform/graphics/ProfilingCanvas.h"
#include "platform/graphics/ReplayingCanvas.h"
#include "platform/image-decoders/ImageDecoder.h"
#include "platform/image-decoders/ImageFrame.h"
#include "platform/image-encoders/skia/PNGImageEncoder.h"
#include "third_party/skia/include/core/SkBitmapDevice.h"
#include "third_party/skia/include/core/SkPictureRecorder.h"
#include "third_party/skia/include/core/SkStream.h"
#include "wtf/HexNumber.h"
#include "wtf/text/Base64.h"
#include "wtf/text/TextEncoding.h"

namespace blink {

GraphicsContext* GraphicsContextRecorder::record(const IntSize& size, bool isCertainlyOpaque)
{
    ASSERT(!m_picture);
    ASSERT(!m_recorder);
    ASSERT(!m_context);
    m_isCertainlyOpaque = isCertainlyOpaque;
    m_recorder = adoptPtr(new SkPictureRecorder);
    SkCanvas* canvas = m_recorder->beginRecording(size.width(), size.height(), 0, 0);
    m_context = adoptPtr(new GraphicsContext(canvas));
    m_context->setRegionTrackingMode(isCertainlyOpaque ? GraphicsContext::RegionTrackingOpaque : GraphicsContext::RegionTrackingDisabled);
    m_context->setCertainlyOpaque(isCertainlyOpaque);
    return m_context.get();
}

PassRefPtr<GraphicsContextSnapshot> GraphicsContextRecorder::stop()
{
    m_context.clear();
    m_picture = adoptRef(m_recorder->endRecording());
    m_recorder.clear();
    return adoptRef(new GraphicsContextSnapshot(m_picture.release()));
}

GraphicsContextSnapshot::GraphicsContextSnapshot(PassRefPtr<SkPicture> picture)
    : m_picture(picture)
{
}

static bool decodeBitmap(const void* data, size_t length, SkBitmap* result)
{
    RefPtr<SharedBuffer> buffer = SharedBuffer::create(static_cast<const char*>(data), length);
    OwnPtr<ImageDecoder> imageDecoder = ImageDecoder::create(*buffer, ImageSource::AlphaPremultiplied, ImageSource::GammaAndColorProfileIgnored);
    if (!imageDecoder)
        return false;
    imageDecoder->setData(buffer.get(), true);
    ImageFrame* frame = imageDecoder->frameBufferAtIndex(0);
    if (!frame)
        return true;
    *result = frame->getSkBitmap();
    return true;
}

PassRefPtr<GraphicsContextSnapshot> GraphicsContextSnapshot::load(const char* data, size_t size)
{
    SkMemoryStream stream(data, size);
    RefPtr<SkPicture> picture = adoptRef(SkPicture::CreateFromStream(&stream, decodeBitmap));
    if (!picture)
        return nullptr;
    return adoptRef(new GraphicsContextSnapshot(picture));
}

PassOwnPtr<Vector<char> > GraphicsContextSnapshot::replay(unsigned fromStep, unsigned toStep, double scale) const
{
    int width = ceil(scale * m_picture->width());
    int height = ceil(scale * m_picture->height());
    SkBitmap bitmap;
    bitmap.allocPixels(SkImageInfo::MakeN32Premul(width, height));
    {
        ReplayingCanvas canvas(bitmap, fromStep, toStep);
        canvas.scale(scale, scale);
        canvas.resetStepCount();
        m_picture->draw(&canvas, &canvas);
    }
    OwnPtr<Vector<char> > base64Data = adoptPtr(new Vector<char>());
    Vector<char> encodedImage;
    if (!PNGImageEncoder::encode(bitmap, reinterpret_cast<Vector<unsigned char>*>(&encodedImage)))
        return nullptr;
    base64Encode(encodedImage, *base64Data);
    return base64Data.release();
}

PassOwnPtr<GraphicsContextSnapshot::Timings> GraphicsContextSnapshot::profile(unsigned minRepeatCount, double minDuration) const
{
    OwnPtr<GraphicsContextSnapshot::Timings> timings = adoptPtr(new GraphicsContextSnapshot::Timings());
    timings->reserveCapacity(minRepeatCount);
    SkBitmap bitmap;
    bitmap.allocPixels(SkImageInfo::MakeN32Premul(m_picture->width(), m_picture->height()));
    OwnPtr<ProfilingCanvas> canvas = adoptPtr(new ProfilingCanvas(bitmap));

    double now = WTF::monotonicallyIncreasingTime();
    double stopTime = now + minDuration;
    for (unsigned step = 0; step < minRepeatCount || now < stopTime; ++step) {
        timings->append(Vector<double>());
        Vector<double>* currentTimings = &timings->last();
        if (timings->size() > 1)
            currentTimings->reserveCapacity(timings->begin()->size());
        if (step)
            canvas = adoptPtr(new ProfilingCanvas(bitmap));
        canvas->setTimings(currentTimings);
        m_picture->draw(canvas.get());
        now = WTF::monotonicallyIncreasingTime();
    }
    return timings.release();
}

PassRefPtr<JSONArray> GraphicsContextSnapshot::snapshotCommandLog() const
{
    LoggingCanvas canvas(m_picture->width(), m_picture->height());
    m_picture->draw(&canvas);
    return canvas.log();
}

} // namespace blink
<commit_msg>Paint Profiler: erase bitmap before replaying SkPicture<commit_after>/*
 * Copyright (C) 2013 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "platform/graphics/GraphicsContextRecorder.h"

#include "platform/graphics/ImageBuffer.h"
#include "platform/graphics/ImageSource.h"
#include "platform/graphics/LoggingCanvas.h"
#include "platform/graphics/ProfilingCanvas.h"
#include "platform/graphics/ReplayingCanvas.h"
#include "platform/image-decoders/ImageDecoder.h"
#include "platform/image-decoders/ImageFrame.h"
#include "platform/image-encoders/skia/PNGImageEncoder.h"
#include "third_party/skia/include/core/SkBitmapDevice.h"
#include "third_party/skia/include/core/SkPictureRecorder.h"
#include "third_party/skia/include/core/SkStream.h"
#include "wtf/HexNumber.h"
#include "wtf/text/Base64.h"
#include "wtf/text/TextEncoding.h"

namespace blink {

GraphicsContext* GraphicsContextRecorder::record(const IntSize& size, bool isCertainlyOpaque)
{
    ASSERT(!m_picture);
    ASSERT(!m_recorder);
    ASSERT(!m_context);
    m_isCertainlyOpaque = isCertainlyOpaque;
    m_recorder = adoptPtr(new SkPictureRecorder);
    SkCanvas* canvas = m_recorder->beginRecording(size.width(), size.height(), 0, 0);
    m_context = adoptPtr(new GraphicsContext(canvas));
    m_context->setRegionTrackingMode(isCertainlyOpaque ? GraphicsContext::RegionTrackingOpaque : GraphicsContext::RegionTrackingDisabled);
    m_context->setCertainlyOpaque(isCertainlyOpaque);
    return m_context.get();
}

PassRefPtr<GraphicsContextSnapshot> GraphicsContextRecorder::stop()
{
    m_context.clear();
    m_picture = adoptRef(m_recorder->endRecording());
    m_recorder.clear();
    return adoptRef(new GraphicsContextSnapshot(m_picture.release()));
}

GraphicsContextSnapshot::GraphicsContextSnapshot(PassRefPtr<SkPicture> picture)
    : m_picture(picture)
{
}

static bool decodeBitmap(const void* data, size_t length, SkBitmap* result)
{
    RefPtr<SharedBuffer> buffer = SharedBuffer::create(static_cast<const char*>(data), length);
    OwnPtr<ImageDecoder> imageDecoder = ImageDecoder::create(*buffer, ImageSource::AlphaPremultiplied, ImageSource::GammaAndColorProfileIgnored);
    if (!imageDecoder)
        return false;
    imageDecoder->setData(buffer.get(), true);
    ImageFrame* frame = imageDecoder->frameBufferAtIndex(0);
    if (!frame)
        return true;
    *result = frame->getSkBitmap();
    return true;
}

PassRefPtr<GraphicsContextSnapshot> GraphicsContextSnapshot::load(const char* data, size_t size)
{
    SkMemoryStream stream(data, size);
    RefPtr<SkPicture> picture = adoptRef(SkPicture::CreateFromStream(&stream, decodeBitmap));
    if (!picture)
        return nullptr;
    return adoptRef(new GraphicsContextSnapshot(picture));
}

PassOwnPtr<Vector<char> > GraphicsContextSnapshot::replay(unsigned fromStep, unsigned toStep, double scale) const
{
    int width = ceil(scale * m_picture->width());
    int height = ceil(scale * m_picture->height());
    SkBitmap bitmap;
    bitmap.allocPixels(SkImageInfo::MakeN32Premul(width, height));
    bitmap.eraseARGB(0, 0, 0, 0);
    {
        ReplayingCanvas canvas(bitmap, fromStep, toStep);
        canvas.scale(scale, scale);
        canvas.resetStepCount();
        m_picture->draw(&canvas, &canvas);
    }
    OwnPtr<Vector<char> > base64Data = adoptPtr(new Vector<char>());
    Vector<char> encodedImage;
    if (!PNGImageEncoder::encode(bitmap, reinterpret_cast<Vector<unsigned char>*>(&encodedImage)))
        return nullptr;
    base64Encode(encodedImage, *base64Data);
    return base64Data.release();
}

PassOwnPtr<GraphicsContextSnapshot::Timings> GraphicsContextSnapshot::profile(unsigned minRepeatCount, double minDuration) const
{
    OwnPtr<GraphicsContextSnapshot::Timings> timings = adoptPtr(new GraphicsContextSnapshot::Timings());
    timings->reserveCapacity(minRepeatCount);
    SkBitmap bitmap;
    bitmap.allocPixels(SkImageInfo::MakeN32Premul(m_picture->width(), m_picture->height()));
    OwnPtr<ProfilingCanvas> canvas = adoptPtr(new ProfilingCanvas(bitmap));

    double now = WTF::monotonicallyIncreasingTime();
    double stopTime = now + minDuration;
    for (unsigned step = 0; step < minRepeatCount || now < stopTime; ++step) {
        timings->append(Vector<double>());
        Vector<double>* currentTimings = &timings->last();
        if (timings->size() > 1)
            currentTimings->reserveCapacity(timings->begin()->size());
        if (step)
            canvas = adoptPtr(new ProfilingCanvas(bitmap));
        canvas->setTimings(currentTimings);
        m_picture->draw(canvas.get());
        now = WTF::monotonicallyIncreasingTime();
    }
    return timings.release();
}

PassRefPtr<JSONArray> GraphicsContextSnapshot::snapshotCommandLog() const
{
    LoggingCanvas canvas(m_picture->width(), m_picture->height());
    m_picture->draw(&canvas);
    return canvas.log();
}

} // namespace blink
<|endoftext|>


<commit_before><commit_msg>Update asio.cpp: fix assert<commit_after><|endoftext|>


<commit_before>#include "Zenderer/CoreGraphics/VertexArray.hpp"

using namespace zen::gfxcore;

CVertexArray::CVertexArray(const GLenum type) :
    CGLSubsystem("Vertex Array"),
    m_icount(0), m_vcount(0),
    m_vao(0), m_vbo(0), m_ibo(0),
    m_type(type)
{
    m_vaoIndices.clear();
    m_vaoVertices.clear();
}

CVertexArray::~CVertexArray()
{
    this->Destroy();
}

bool CVertexArray::Init()
{
    if(m_init) this->Destroy();

    // Bad GL version.
    if(!glGenVertexArrays) return false;

    GL(glGenVertexArrays(1, &m_vao));
    GL(glGenBuffers(1, &m_vbo));
    GL(glGenBuffers(1, &m_ibo));

    ZEN_ASSERT(m_vao != 0);
    ZEN_ASSERT(m_vbo != 0);
    ZEN_ASSERT(m_ibo != 0);

    return (m_init = true);
}

bool CVertexArray::Destroy()
{
    if(!m_init) return true;

    ZEN_ASSERT(m_vao != 0);
    ZEN_ASSERT(m_vbo != 0);
    ZEN_ASSERT(m_ibo != 0);

    glDeleteVertexArrays(1, &m_vao);
    glDeleteBuffers(1, &m_vbo);
    glDeleteBuffers(1, &m_ibo);

    return true;
}

bool CVertexArray::Bind()
{
    if(!this->Init()) return false;

    GL(glBindVertexArray(m_vao));
    GL(glEnableVertexAttribArray(0));       // Enable shader attribute 0
    GL(glEnableVertexAttribArray(1));
    GL(glEnableVertexAttribArray(2));
    return true;
}

bool CVertexArray::Unbind()
{
    if(!this->Init()) return false;

    GL(glBindVertexArray(0));

    return true;
}

index_t CVertexArray::AddData(const DrawBatch& D)
{
    ZEN_ASSERTM(D.vcount > 0, "no buffer vertices given");
    ZEN_ASSERTM(D.icount > 0, "no buffer indices given");

    m_vaoVertices.resize(m_vaoVertices.size() + D.vcount);
    for(size_t v = 0; v < D.vcount; ++v)
        m_vaoVertices.push_back(D.Vertices[v]);

    size_t offset = m_vaoIndices.size();

    m_vaoIndices.resize(m_vaoIndices.size() + D.icount);
    for(size_t i = 0; i < D.icount; ++i)
        m_vaoIndices.push_back(D.Indices[i]);

    return offset + m_icount;
}

bool CVertexArray::Offload()
{
    if(!this->Bind())       return false;
    if(this->Offloaded())   return false;

    // Check if there's existing data on the buffers.
    GLint bsize = 0;
    glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &bsize);

    // There is!
    if(bsize > 0)
    {
        // Copy existing buffer data from GPU to local buffer.
        const vertex_t* const data = this->GetVerticesFromGPU();
        vertex_t* tmp  = new vertex_t[bsize / sizeof(vertex_t)];
        memcpy(tmp, data, bsize);
        glUnmapBuffer(GL_ARRAY_BUFFER);

        // Allocate enough GPU space for all vertex data, new and old.
        // Pass the old data directly to it.
        glBufferData(GL_ARRAY_BUFFER,
                     bsize + (sizeof(vertex_t) * m_vaoVertices.size()),
                     tmp, m_type);

        // Pass the latest vertex data at the end of the existing data.
        glBufferSubData(GL_ARRAY_BUFFER, bsize,
                        sizeof(vertex_t) * m_vaoVertices.size(),
                        &m_vaoVertices[0]);
    }
    // No existing buffer or vertices.
    else
    {
        // Allocate enough space for all vertices on GPU.
        glBufferData(GL_ARRAY_BUFFER,
                     sizeof(vertex_t) * m_vaoVertices.size(),
                     &m_vaoVertices[0], m_type);
    }

    // Repeat process for index buffer.
    bsize = 0;
    glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &bsize);

    if(bsize > 0)
    {
        // Copy from GPU to local buffer.
        const index_t* const data = this->GetIndicesFromGPU();
        index_t* tmp  = new index_t[bsize / sizeof(index_t)];
        memcpy(tmp, data, bsize);
        glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);

        // Allocate enough GPU space for all vertex data, new and old.
        // Pass the old data directly to it.
        glBufferData(GL_ELEMENT_ARRAY_BUFFER,                         // IBO
                     bsize + (sizeof(index_t) * m_vaoIndices.size()), // Size
                     tmp,       // Initial data
                     m_type);   // Access type

        // Pass the latest vertex data at the end of the existing data.
        glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, bsize,
                        sizeof(index_t) * m_vaoIndices.size(),
                        &m_vaoIndices[0]);
    }
    else
    {
        // No existing data, so we just write new stuff to the buffer.
        glBufferData(GL_ELEMENT_ARRAY_BUFFER,
                     sizeof(index_t) * m_vaoIndices.size(),
                     &m_vaoIndices[0], m_type);
    }

    // Vertices are arranged in memory like so:
    //
    // [ x, y, z, t, s, r, r, g, b, a ]
    //
    // (see the definition of vertex_t in Zenderer/CoreGraphics/OpenGL.hpp)
    //
    // Specify vertex position arrangement.
    // According to the diagram shown above, the vertex position
    // would start at index 0.
    glVertexAttribPointer(0,                /* Attribute index  */
                          3,                /* Number of values */
                          GL_FLOAT,         /* Type of value    */
                          GL_FALSE,         /* Normalized?      */
                          sizeof(vertex_t), /* Size of field    */
        VBO_OFFSET(0, vertex_t, position)); /* Size of offset   */

    // Specify texture coordinate position arrangement.
    // According to the diagram, texture coordinates
    // start at index 3.
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(vertex_t),
                          VBO_OFFSET(0, vertex_t, tc));

    // Specify the color arrangement, starting at index 4.
    glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(vertex_t),
                          VBO_OFFSET(0, vertex_t, color));

    // We're done, clean up buffers.
    m_vcount += m_vaoVertices.size();
    m_icount += m_vaoIndices.size();

    m_vaoVertices.clear();
    m_vaoIndices.clear();

    return this->Unbind();
}

const vertex_t* const CVertexArray::GetVerticesFromGPU() const
{
    return (vertex_t*)glMapBuffer(GL_ARRAY_BUFFER, GL_READ_ONLY);
}

const index_t* const CVertexArray::GetIndicesFromGPU() const
{
    return (index_t*)glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_READ_ONLY);
}

size_t CVertexArray::GetVertexCount() const
{
    return m_vcount;
}

size_t CVertexArray::GetIndexCount() const
{
    return m_icount;
}

bool CVertexArray::Offloaded() const
{
    return (m_vaoIndices.size() > 0 && m_vaoVertices.size() > 0);
}
<commit_msg>Critical VAO bugfix<commit_after>#include "Zenderer/CoreGraphics/VertexArray.hpp"

using namespace zen::gfxcore;

CVertexArray::CVertexArray(const GLenum type) :
    CGLSubsystem("Vertex Array"),
    m_icount(0), m_vcount(0),
    m_vao(0), m_vbo(0), m_ibo(0),
    m_type(type)
{
    m_vaoIndices.clear();
    m_vaoVertices.clear();
}

CVertexArray::~CVertexArray()
{
    this->Destroy();
}

bool CVertexArray::Init()
{
    if(m_init) this->Destroy();

    // Bad GL version.
    if(!glGenVertexArrays) return false;

    GL(glGenVertexArrays(1, &m_vao));
    GL(glGenBuffers(1, &m_vbo));
    GL(glGenBuffers(1, &m_ibo));

    ZEN_ASSERT(m_vao != 0);
    ZEN_ASSERT(m_vbo != 0);
    ZEN_ASSERT(m_ibo != 0);

    return (m_init = true);
}

bool CVertexArray::Destroy()
{
    if(!m_init) return true;

    ZEN_ASSERT(m_vao != 0);
    ZEN_ASSERT(m_vbo != 0);
    ZEN_ASSERT(m_ibo != 0);

    glDeleteVertexArrays(1, &m_vao);
    glDeleteBuffers(1, &m_vbo);
    glDeleteBuffers(1, &m_ibo);

    return true;
}

bool CVertexArray::Bind()
{
    if(!m_init) return false;

    GL(glBindVertexArray(m_vao));
    GL(glEnableVertexAttribArray(0));       // Enable shader attribute 0
    GL(glEnableVertexAttribArray(1));
    GL(glEnableVertexAttribArray(2));
    return true;
}

bool CVertexArray::Unbind()
{
    if(!this->Init()) return false;

    GL(glBindVertexArray(0));

    return true;
}

index_t CVertexArray::AddData(const DrawBatch& D)
{
    ZEN_ASSERTM(D.vcount > 0, "no buffer vertices given");
    ZEN_ASSERTM(D.icount > 0, "no buffer indices given");

    m_vaoVertices.resize(m_vaoVertices.size() + D.vcount);
    for(size_t v = 0; v < D.vcount; ++v)
        m_vaoVertices.push_back(D.Vertices[v]);

    size_t offset = m_vaoIndices.size();

    m_vaoIndices.resize(m_vaoIndices.size() + D.icount);
    for(size_t i = 0; i < D.icount; ++i)
        m_vaoIndices.push_back(D.Indices[i]);

    return offset + m_icount;
}

bool CVertexArray::Offload()
{
    if(!this->Bind())       return false;
    if(this->Offloaded())   return false;

    // Check if there's existing data on the buffers.
    GLint bsize = 0;
    glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &bsize);

    // There is!
    if(bsize > 0)
    {
        // Copy existing buffer data from GPU to local buffer.
        const vertex_t* const data = this->GetVerticesFromGPU();
        vertex_t* tmp  = new vertex_t[bsize / sizeof(vertex_t)];
        memcpy(tmp, data, bsize);
        glUnmapBuffer(GL_ARRAY_BUFFER);

        // Allocate enough GPU space for all vertex data, new and old.
        // Pass the old data directly to it.
        glBufferData(GL_ARRAY_BUFFER,
                     bsize + (sizeof(vertex_t) * m_vaoVertices.size()),
                     tmp, m_type);

        // Pass the latest vertex data at the end of the existing data.
        glBufferSubData(GL_ARRAY_BUFFER, bsize,
                        sizeof(vertex_t) * m_vaoVertices.size(),
                        &m_vaoVertices[0]);
    }
    // No existing buffer or vertices.
    else
    {
        // Allocate enough space for all vertices on GPU.
        glBufferData(GL_ARRAY_BUFFER,
                     sizeof(vertex_t) * m_vaoVertices.size(),
                     &m_vaoVertices[0], m_type);
    }

    // Repeat process for index buffer.
    bsize = 0;
    glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &bsize);

    if(bsize > 0)
    {
        // Copy from GPU to local buffer.
        const index_t* const data = this->GetIndicesFromGPU();
        index_t* tmp  = new index_t[bsize / sizeof(index_t)];
        memcpy(tmp, data, bsize);
        glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);

        // Allocate enough GPU space for all vertex data, new and old.
        // Pass the old data directly to it.
        glBufferData(GL_ELEMENT_ARRAY_BUFFER,                         // IBO
                     bsize + (sizeof(index_t) * m_vaoIndices.size()), // Size
                     tmp,       // Initial data
                     m_type);   // Access type

        // Pass the latest vertex data at the end of the existing data.
        glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, bsize,
                        sizeof(index_t) * m_vaoIndices.size(),
                        &m_vaoIndices[0]);
    }
    else
    {
        // No existing data, so we just write new stuff to the buffer.
        glBufferData(GL_ELEMENT_ARRAY_BUFFER,
                     sizeof(index_t) * m_vaoIndices.size(),
                     &m_vaoIndices[0], m_type);
    }

    // Vertices are arranged in memory like so:
    //
    // [ x, y, z, t, s, r, r, g, b, a ]
    //
    // (see the definition of vertex_t in Zenderer/CoreGraphics/OpenGL.hpp)
    //
    // Specify vertex position arrangement.
    // According to the diagram shown above, the vertex position
    // would start at index 0.
    glVertexAttribPointer(0,                /* Attribute index  */
                          3,                /* Number of values */
                          GL_FLOAT,         /* Type of value    */
                          GL_FALSE,         /* Normalized?      */
                          sizeof(vertex_t), /* Size of field    */
        VBO_OFFSET(0, vertex_t, position)); /* Size of offset   */

    // Specify texture coordinate position arrangement.
    // According to the diagram, texture coordinates
    // start at index 3.
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(vertex_t),
                          VBO_OFFSET(0, vertex_t, tc));

    // Specify the color arrangement, starting at index 4.
    glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(vertex_t),
                          VBO_OFFSET(0, vertex_t, color));

    // We're done, clean up buffers.
    m_vcount += m_vaoVertices.size();
    m_icount += m_vaoIndices.size();

    m_vaoVertices.clear();
    m_vaoIndices.clear();

    return this->Unbind();
}

const vertex_t* const CVertexArray::GetVerticesFromGPU() const
{
    return (vertex_t*)glMapBuffer(GL_ARRAY_BUFFER, GL_READ_ONLY);
}

const index_t* const CVertexArray::GetIndicesFromGPU() const
{
    return (index_t*)glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_READ_ONLY);
}

size_t CVertexArray::GetVertexCount() const
{
    return m_vcount;
}

size_t CVertexArray::GetIndexCount() const
{
    return m_icount;
}

bool CVertexArray::Offloaded() const
{
    return (m_vaoIndices.size() == 0 && m_vaoVertices.size() == 0);
}
<|endoftext|>


<commit_before>
// GridStructGen.cpp

// Implements the cGridStructGen class representing a common base class for structure generators that place structures in a semi-random grid

#include "Globals.h"
#include "GridStructGen.h"

cGridStructGen::cGridStructGen(
	int a_Seed,
	int a_GridSizeX, int a_GridSizeZ,
	int a_MaxStructureSizeX, int a_MaxStructureSizeZ,
	size_t a_MaxCacheSize
) :
	m_Seed(a_Seed),
	m_GridSizeX(a_GridSizeX),
	m_GridSizeZ(a_GridSizeZ),
	m_MaxStructureSizeX(a_MaxStructureSizeX),
	m_MaxStructureSizeZ(a_MaxStructureSizeZ),
	m_MaxCacheSize(a_MaxCacheSize)
{
}

void cGridStructGen::GetStructuresForChunk(int a_ChunkX, int a_ChunkZ, cStructurePtrs & a_Structures)
{
	// Calculate the min and max grid coords of the structures to be returned:
	int MinBlockX = a_ChunkX * cChunkDef::Width - m_MaxStructureSizeX;
	int MinBlockZ = a_ChunkZ * cChunkDef::Width - m_MaxStructureSizeZ;
	int MaxBlockX = a_ChunkX * cChunkDef::Width + m_MaxStructureSizeX + cChunkDef::Width - 1;
	int MaxBlockZ = a_ChunkZ * cChunkDef::Width + m_MaxStructureSizeZ + cChunkDef::Width - 1;
	int MinGridX = MinBlockX / m_GridSizeX;
	int MinGridZ = MinBlockZ / m_GridSizeZ;
	int MaxGridX = (MaxBlockX + m_GridSizeX - 1) / m_GridSizeX;
	int MaxGridZ = (MaxBlockZ + m_GridSizeZ - 1) / m_GridSizeZ;
	if (MinBlockX < 0)
	{
		--MinGridX;
	}
	if (MinBlockZ < 0)
	{
		--MinGridZ;
	}
	if (MaxBlockX < 0)
	{
		--MaxGridX;
	}
	if (MaxBlockZ < 0)
	{
		--MaxGridZ;
	}

	// Walk the cache, move each structure that we want into a_Structures:
	for (cStructurePtrs::iterator itr = m_Cache.begin(), end = m_Cache.end(); itr != end;)
	{
		if (
			((*itr)->m_OriginX >= MinBlockX) && ((*itr)->m_OriginX < MaxBlockX) &&
			((*itr)->m_OriginZ >= MinBlockZ) && ((*itr)->m_OriginZ < MaxBlockZ)
		)
		{
			// want
			a_Structures.push_back(*itr);
			itr = m_Cache.erase(itr);
		}
		else
		{
			// don't want
			++itr;
		}
	}  // for itr - m_Cache[]

	// Create those structures that haven't been in the cache:
	for (int x = MinGridX; x < MaxGridX; x++)
	{
		int OriginX = x * m_GridSizeX;
		for (int z = MinGridZ; z < MaxGridZ; z++)
		{
			int OriginZ = z * m_GridSizeZ;
			bool Found = false;
			for (cStructurePtrs::const_iterator itr = a_Structures.begin(), end = a_Structures.end(); itr != end; ++itr)
			{
				if (((*itr)->m_OriginX == OriginX) && ((*itr)->m_OriginZ == OriginZ))
				{
					Found = true;
					break;
				}
			}  // for itr - a_Structures[]
			if (!Found)
			{
				a_Structures.push_back(CreateStructure(OriginX, OriginZ));
			}
		}  // for z
	}  // for x

	// Copy a_Forts into m_Cache to the beginning:
	cStructurePtrs StructuresCopy (a_Structures);
	m_Cache.splice(m_Cache.begin(), StructuresCopy, StructuresCopy.begin(), StructuresCopy.end());

	// Trim the cache if it's too long:
	size_t CacheSize = 0;
	for (cStructurePtrs::iterator itr = m_Cache.begin(), end = m_Cache.end(); itr != end; ++itr)
	{
		CacheSize += (*itr)->GetCacheCost();
		if (CacheSize > m_MaxCacheSize)
		{
			// Erase all items from this one till the cache end
			m_Cache.erase(itr, m_Cache.end());
			break;
		}
	}
}

void cGridStructGen::GenFinish(cChunkDesc & a_ChunkDesc)
{
	int ChunkX = a_ChunkDesc.GetChunkX();
	int ChunkZ = a_ChunkDesc.GetChunkZ();
	cStructurePtrs Structures;
	GetStructuresForChunk(ChunkX, ChunkZ, Structures);
	for (cStructurePtrs::const_iterator itr = Structures.begin(); itr != Structures.end(); ++itr)
	{
		(*itr)->DrawIntoChunk(a_ChunkDesc);
	}  // for itr - Structures[]
}

<commit_msg>Fixed cGridStructGen.<commit_after>
// GridStructGen.cpp

// Implements the cGridStructGen class representing a common base class for structure generators that place structures in a semi-random grid

#include "Globals.h"
#include "GridStructGen.h"

cGridStructGen::cGridStructGen(
	int a_Seed,
	int a_GridSizeX, int a_GridSizeZ,
	int a_MaxStructureSizeX, int a_MaxStructureSizeZ,
	size_t a_MaxCacheSize
) :
	m_Seed(a_Seed),
	m_GridSizeX(a_GridSizeX),
	m_GridSizeZ(a_GridSizeZ),
	m_MaxStructureSizeX(a_MaxStructureSizeX),
	m_MaxStructureSizeZ(a_MaxStructureSizeZ),
	m_MaxCacheSize(a_MaxCacheSize)
{
}

void cGridStructGen::GetStructuresForChunk(int a_ChunkX, int a_ChunkZ, cStructurePtrs & a_Structures)
{
	// Calculate the min and max grid coords of the structures to be returned:
	int MinBlockX = a_ChunkX * cChunkDef::Width - m_MaxStructureSizeX;
	int MinBlockZ = a_ChunkZ * cChunkDef::Width - m_MaxStructureSizeZ;
	int MaxBlockX = a_ChunkX * cChunkDef::Width + m_MaxStructureSizeX + cChunkDef::Width - 1;
	int MaxBlockZ = a_ChunkZ * cChunkDef::Width + m_MaxStructureSizeZ + cChunkDef::Width - 1;
	int MinGridX = MinBlockX / m_GridSizeX;
	int MinGridZ = MinBlockZ / m_GridSizeZ;
	int MaxGridX = (MaxBlockX + m_GridSizeX - 1) / m_GridSizeX;
	int MaxGridZ = (MaxBlockZ + m_GridSizeZ - 1) / m_GridSizeZ;
	int MinX = MinGridX * m_GridSizeX;
	int MaxX = MaxGridX * m_GridSizeX;
	int MinZ = MinGridZ * m_GridSizeZ;
	int MaxZ = MaxGridZ * m_GridSizeZ;

	// Walk the cache, move each structure that we want into a_Structures:
	for (cStructurePtrs::iterator itr = m_Cache.begin(), end = m_Cache.end(); itr != end;)
	{
		if (
			((*itr)->m_OriginX >= MinX) && ((*itr)->m_OriginX < MaxX) &&
			((*itr)->m_OriginZ >= MinZ) && ((*itr)->m_OriginZ < MaxZ)
		)
		{
			// want
			a_Structures.push_back(*itr);
			itr = m_Cache.erase(itr);
		}
		else
		{
			// don't want
			++itr;
		}
	}  // for itr - m_Cache[]

	// Create those structures that haven't been in the cache:
	for (int x = MinGridX; x < MaxGridX; x++)
	{
		int OriginX = x * m_GridSizeX;
		for (int z = MinGridZ; z < MaxGridZ; z++)
		{
			int OriginZ = z * m_GridSizeZ;
			bool Found = false;
			for (cStructurePtrs::const_iterator itr = a_Structures.begin(), end = a_Structures.end(); itr != end; ++itr)
			{
				if (((*itr)->m_OriginX == OriginX) && ((*itr)->m_OriginZ == OriginZ))
				{
					Found = true;
					break;
				}
			}  // for itr - a_Structures[]
			if (!Found)
			{
				a_Structures.push_back(CreateStructure(OriginX, OriginZ));
			}
		}  // for z
	}  // for x

	// Copy a_Forts into m_Cache to the beginning:
	cStructurePtrs StructuresCopy (a_Structures);
	m_Cache.splice(m_Cache.begin(), StructuresCopy, StructuresCopy.begin(), StructuresCopy.end());

	// Trim the cache if it's too long:
	size_t CacheSize = 0;
	for (cStructurePtrs::iterator itr = m_Cache.begin(), end = m_Cache.end(); itr != end; ++itr)
	{
		CacheSize += (*itr)->GetCacheCost();
		if (CacheSize > m_MaxCacheSize)
		{
			// Erase all items from this one till the cache end
			m_Cache.erase(itr, m_Cache.end());
			break;
		}
	}
}

void cGridStructGen::GenFinish(cChunkDesc & a_ChunkDesc)
{
	int ChunkX = a_ChunkDesc.GetChunkX();
	int ChunkZ = a_ChunkDesc.GetChunkZ();
	cStructurePtrs Structures;
	GetStructuresForChunk(ChunkX, ChunkZ, Structures);
	for (cStructurePtrs::const_iterator itr = Structures.begin(); itr != Structures.end(); ++itr)
	{
		(*itr)->DrawIntoChunk(a_ChunkDesc);
	}  // for itr - Structures[]
}

<|endoftext|>


<commit_before>#include "MatrixOptimizationDataTx.hpp"
#include "SparseMatrix.hpp"
#include "KernelWrappers.h"

#ifndef HPCG_NOMPI
#include "ExchangeHalo.hpp"
#include "mpi.h"
#endif

MatrixOptimizationDataTx::MatrixOptimizationDataTx()
    : handle(0), matDescr(0), localMatrix(0), gsContext(0), f2c(0),
      workvector(0) {
  cusparseStatus_t err = cusparseCreate(&handle);
  CHKCUSPARSEERR(err);
}

MatrixOptimizationDataTx::~MatrixOptimizationDataTx() {
  if (handle) {
    cusparseDestroy(handle);
    handle = 0;
  }
  if (matDescr) {
    cusparseDestroyMatDescr(matDescr);
    matDescr = 0;
  }
  if (localMatrix) {
    cusparseDestroyHybMat(localMatrix);
    localMatrix = 0;
  }
  if (gsContext) {
    cugelusDestroySorIterationData(gsContext);
    gsContext = 0;
  }
  if (f2c) {
    CHKCUDAERR(cudaFree(f2c));
  }
  if (workvector) {
    CHKCUDAERR(cudaFree(workvector));
  }
}

int MatrixOptimizationDataTx::setupLocalMatrixOnGPU(SparseMatrix& A) {
  std::vector<local_int_t> i(A.localNumberOfRows + 1, 0);
  std::vector<local_int_t> j(A.localNumberOfNonzeros, 0);
  std::vector<double> a(A.localNumberOfNonzeros, 0);
  for (local_int_t m = 0; m < A.localNumberOfRows; ++m) {
    i[m + 1] = i[m] + A.nonzerosInRow[m];
  }
  local_int_t index = 0;
  for (local_int_t m = 0; m < A.localNumberOfRows; ++m) {
    for (local_int_t n = 0; n < A.nonzerosInRow[m]; ++n) {
      j[index] = A.mtxIndL[m][n];
      ++index;
    }
  }
  index = 0;
  for (local_int_t m = 0; m < A.localNumberOfRows; ++m) {
    for (local_int_t n = 0; n < A.nonzerosInRow[m]; ++n) {
      a[index] = A.matrixValues[m][n];
      ++index;
    }
  }

  cudaError_t err = cudaSuccess;
  int* i_d;
  err = cudaMalloc((void**)&i_d, i.size() * sizeof(i[0]));
  CHKCUDAERR(err);
  err = cudaMemcpy(i_d, &i[0], i.size() * sizeof(i[0]), cudaMemcpyHostToDevice);
  CHKCUDAERR(err);
  int* j_d;
  err = cudaMalloc((void**)&j_d, j.size() * sizeof(j[0]));
  CHKCUDAERR(err);
  err = cudaMemcpy(j_d, &j[0], j.size() * sizeof(j[0]), cudaMemcpyHostToDevice);
  CHKCUDAERR(err);
  double* a_d;
  err = cudaMalloc((void**)&a_d, a.size() * sizeof(a[0]));
  CHKCUDAERR(err);
  err = cudaMemcpy(a_d, &a[0], a.size() * sizeof(a[0]), cudaMemcpyHostToDevice);
  CHKCUDAERR(err);

  cusparseStatus_t cerr = CUSPARSE_STATUS_SUCCESS;
  cerr = cusparseCreateMatDescr(&matDescr);
  CHKCUSPARSEERR(cerr);
  cerr = cusparseSetMatIndexBase(matDescr, CUSPARSE_INDEX_BASE_ZERO);
  CHKCUSPARSEERR(cerr);
  cerr = cusparseSetMatType(matDescr, CUSPARSE_MATRIX_TYPE_GENERAL);
  CHKCUSPARSEERR(cerr);
  cerr = cusparseCreateHybMat(&localMatrix);
  CHKCUSPARSEERR(cerr);
  cerr = cusparseDcsr2hyb(handle, A.localNumberOfRows, A.localNumberOfColumns,
                          matDescr, a_d, i_d, j_d, localMatrix, 27,
                          CUSPARSE_HYB_PARTITION_USER);
  CHKCUSPARSEERR(cerr);

  // Set up the GS data.
  // Need to extract the local portion of the matrix for gelus.
  // The part for scattering from the halo into the local portion of the
  // vector goes into scatterFromHalo.
  j.resize(0);
  a.resize(0);
  scatterFromHalo.setNumRows(A.localNumberOfRows);
  scatterFromHalo.setNumCols(A.localNumberOfColumns);
  scatterFromHalo.clear();
  for (local_int_t m = 0; m < A.localNumberOfRows; ++m) {
    local_int_t nonzerosInRow = 0;
    for (local_int_t n = 0; n < A.nonzerosInRow[m]; ++n) {
      local_int_t col = A.mtxIndL[m][n];
      if (col < A.localNumberOfRows) {
        j.push_back(col);
        a.push_back(A.matrixValues[m][n]);
        ++nonzerosInRow;
      } else {
        scatterFromHalo.addEntry(m, col, A.matrixValues[m][n]);
      }
    }
    i[m + 1] = i[m] + nonzerosInRow;
  }

  gelusStatus_t gerr = GELUS_STATUS_SUCCESS;
  gelusSolveDescription_t solveDescr;
  gerr = gelusCreateSolveDescr(&solveDescr);
  CHKGELUSERR(gerr);
  gerr = gelusSetSolveOperation(solveDescr, GELUS_OPERATION_NON_TRANSPOSE);
  CHKGELUSERR(gerr);
  gerr = gelusSetSolveFillMode(solveDescr, GELUS_FILL_MODE_FULL);
  CHKGELUSERR(gerr);
  gerr = gelusSetSolveStorageFormat(solveDescr, GELUS_STORAGE_FORMAT_HYB);
  CHKGELUSERR(gerr);
  gerr = gelusSetOptimizationLevel(solveDescr, GELUS_OPTIMIZATION_LEVEL_THREE);
  CHKGELUSERR(gerr);

  gerr = cugelusCreateSorIterationData(&gsContext);
  CHKGELUSERR(gerr);

#ifdef HPCG_DEBUG
  std::cout << A.localNumberOfRows << std::endl;
  std::cout << A.localNumberOfColumns << std::endl;
  std::cout << A.localNumberOfNonzeros << std::endl;
  int myrank;
  MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
  if (myrank == 0) {
    dumpMatrix(std::cout, i, j, a);
  }
#endif

  gerr = cugelusDcsrsor_iteration_analysis(
      A.localNumberOfRows, solveDescr, GELUS_SOR_SYMMETRIC, 1.0,
      &i[0], &j[0], &a[0], gsContext);
  gerr = gelusDestroySolveDescr(solveDescr);
  CHKGELUSERR(gerr);

  if (A.mgData) {
    err =
      cudaMalloc((void**)&f2c, A.mgData->rc->localLength * sizeof(local_int_t));
    CHKCUDAERR(err);
    err = cudaMemcpy(f2c, A.mgData->f2cOperator,
        A.mgData->rc->localLength * sizeof(local_int_t),
        cudaMemcpyHostToDevice);
    CHKCUDAERR(err);
  }

  err = cudaMalloc((void**)&workvector, A.localNumberOfRows * sizeof(double));
  CHKCUDAERR(err);

  return (int)cerr | (int)gerr | (int)err;
}

int MatrixOptimizationDataTx::ComputeSPMV(const SparseMatrix& A, Vector& x,
    Vector& y, bool copyIn,
    bool copyOut) {
  double* x_dev = 0;
  double* y_dev = 0;
#ifndef HPCG_NOMPI
  DataTransfer transfer = BeginExchangeHalo(A, x);
  EndExchangeHalo(A, x, transfer);
  x_dev = transferDataToGPU(x);
#endif
  if (copyIn) {
#ifdef HPCG_NOMPI
    x_dev = transferDataToGPU(x);
#endif
    y_dev = transferDataToGPU(y);
  } else {
    x_dev = ((VectorOptimizationDataTx*)x.optimizationData)->devicePtr;
    y_dev = ((VectorOptimizationDataTx*)y.optimizationData)->devicePtr;
  }
  double alpha = 1.0;
  double beta = 0.0;
  cusparseStatus_t cerr;
  cerr = cusparseDhybmv(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, &alpha,
      matDescr, localMatrix, x_dev, &beta, y_dev);
  CHKCUSPARSEERR(cerr);
  if (copyOut) {
    transferDataFromGPU(y);
  }
  return 0;
}

int MatrixOptimizationDataTx::ComputeSYMGS(const SparseMatrix &A,
                                           const Vector &r, Vector &x,
                                           int numberOfSmootherSteps,
                                           bool copyIn, bool copyOut) {
  const double* r_dev = 0;
  double* x_dev = 0;
#ifndef HPCG_NOMPI
  DataTransfer transfer = BeginExchangeHalo(A, x);
  EndExchangeHalo(A, x, transfer);
  x_dev = transferDataToGPU(x);
#endif
  if (copyIn) {
#ifdef HPCG_NOMPI
    x_dev = transferDataToGPU(x);
#endif
    r_dev = transferDataToGPU(r);
  } else {
    x_dev = ((VectorOptimizationDataTx*)x.optimizationData)->devicePtr;
    r_dev = ((VectorOptimizationDataTx*)r.optimizationData)->devicePtr;
  }
  launchDeviceCopy(workvector, r_dev, r.localLength);
  scatterFromHalo.spmv(x_dev, workvector, -1, 1);
  gelusStatus_t err =
      cugelusDcsrsor_iterate(x_dev, workvector, GELUS_SOR_INITIAL_GUESS_NONZERO,
                             numberOfSmootherSteps, gsContext);
  CHKGELUSERR(err);
  if (copyOut) {
    transferDataFromGPU(x);
    transferDataFromGPU(r);
  }
  return 0;
}

int MatrixOptimizationDataTx::ComputeProlongation(const SparseMatrix& Af,
    Vector& xf, bool copyIn, bool copyOut) {
  double* xf_d = 0;
  double* xc_d = 0;
  if (copyIn) {
    xf_d = transferDataToGPU(xf);
    xc_d = transferDataToGPU(*Af.mgData->xc);
  } else {
    xf_d = ((VectorOptimizationDataTx*)xf.optimizationData)->devicePtr;
    xc_d = ((VectorOptimizationDataTx*)Af.mgData->xc->optimizationData)->devicePtr;
  }

  local_int_t nc = Af.mgData->rc->localLength;
  launchProlongationKernel(xf_d, xc_d, nc, f2c);

  if (copyOut) {
    transferDataFromGPU(xf);
    transferDataFromGPU(*Af.mgData->xc);
  }
  return 0;
}

int MatrixOptimizationDataTx::ComputeRestriction(const SparseMatrix& Af,
                                                 const Vector& rf, bool copyIn,
                                                 bool copyOut) {
  double* Axf_d = 0;
  double* rf_d = 0;
  double* rc_d = 0;
  if (copyIn) {
    Axf_d = transferDataToGPU(*Af.mgData->Axf);
    rf_d = transferDataToGPU(rf);
    rc_d = transferDataToGPU(*Af.mgData->rc);
  } else {
    Axf_d = ((VectorOptimizationDataTx*)Af.mgData->Axf->optimizationData)->devicePtr;
    rf_d = ((VectorOptimizationDataTx*)rf.optimizationData)->devicePtr;
    rc_d = ((VectorOptimizationDataTx*)Af.mgData->rc->optimizationData)->devicePtr;
  }

  local_int_t nc = Af.mgData->rc->localLength;
  launchRestrictionKernel(rc_d, rf_d, Axf_d, nc, f2c);

  if (copyOut) {
    transferDataFromGPU(*Af.mgData->Axf);
    transferDataFromGPU(rf);
    transferDataFromGPU(*Af.mgData->rc);
  }
  return 0;
}

void dumpMatrix(std::ostream& s, const std::vector<int>& i,
    const std::vector<int>& j, const std::vector<double>& a)
{
  s << "%%MatrixMarket matrix coordinate real general\n";
  int numRows = i.size() - 1;
  int nnz = j.size();
  s << numRows << " " << numRows << " " << nnz << "\n";
  for (int m = 0; m < numRows; ++m) {
    for (int n = i[m]; n < i[m + 1]; ++n) {
      s << m + 1 << " " << j[n] + 1 << " " << a[n] << "\n";
    }
  }
}
<commit_msg>Break matrix up into diagonal and off-diagonal block.<commit_after>#include "MatrixOptimizationDataTx.hpp"
#include "SparseMatrix.hpp"
#include "KernelWrappers.h"

#ifndef HPCG_NOMPI
#include "ExchangeHalo.hpp"
#include "mpi.h"
#endif

MatrixOptimizationDataTx::MatrixOptimizationDataTx()
    : handle(0), matDescr(0), localMatrix(0), gsContext(0), f2c(0),
      workvector(0) {
  cusparseStatus_t err = cusparseCreate(&handle);
  CHKCUSPARSEERR(err);
}

MatrixOptimizationDataTx::~MatrixOptimizationDataTx() {
  if (handle) {
    cusparseDestroy(handle);
    handle = 0;
  }
  if (matDescr) {
    cusparseDestroyMatDescr(matDescr);
    matDescr = 0;
  }
  if (localMatrix) {
    cusparseDestroyHybMat(localMatrix);
    localMatrix = 0;
  }
  if (gsContext) {
    cugelusDestroySorIterationData(gsContext);
    gsContext = 0;
  }
  if (f2c) {
    CHKCUDAERR(cudaFree(f2c));
  }
  if (workvector) {
    CHKCUDAERR(cudaFree(workvector));
  }
}

int MatrixOptimizationDataTx::setupLocalMatrixOnGPU(SparseMatrix& A) {
  std::vector<local_int_t> i(A.localNumberOfRows + 1, 0);
  std::vector<local_int_t> j(A.localNumberOfNonzeros, 0);
  std::vector<double> a(A.localNumberOfNonzeros, 0);
  scatterFromHalo.setNumRows(A.localNumberOfRows);
  scatterFromHalo.setNumCols(A.localNumberOfColumns);
  scatterFromHalo.clear();
  // We're splitting the matrix into diagonal and off-diagonal block to
  // enable overlapping of computation and communication.
  for (local_int_t m = 0; m < A.localNumberOfRows; ++m) {
    local_int_t nonzerosInRow = 0;
    for (local_int_t n = 0; n < A.nonzerosInRow[m]; ++n) {
      local_int_t col = A.mtxIndL[m][n];
      if (col < A.localNumberOfRows) {
        j.push_back(col);
        a.push_back(A.matrixValues[m][n]);
        ++nonzerosInRow;
      } else {
        scatterFromHalo.addEntry(m, col, A.matrixValues[m][n]);
      }
    }
    i[m + 1] = i[m] + nonzerosInRow;
  }

  // Setup SpMV data on GPU
  cudaError_t err = cudaSuccess;
  int* i_d;
  err = cudaMalloc((void**)&i_d, i.size() * sizeof(i[0]));
  CHKCUDAERR(err);
  err = cudaMemcpy(i_d, &i[0], i.size() * sizeof(i[0]), cudaMemcpyHostToDevice);
  CHKCUDAERR(err);
  int* j_d;
  err = cudaMalloc((void**)&j_d, j.size() * sizeof(j[0]));
  CHKCUDAERR(err);
  err = cudaMemcpy(j_d, &j[0], j.size() * sizeof(j[0]), cudaMemcpyHostToDevice);
  CHKCUDAERR(err);
  double* a_d;
  err = cudaMalloc((void**)&a_d, a.size() * sizeof(a[0]));
  CHKCUDAERR(err);
  err = cudaMemcpy(a_d, &a[0], a.size() * sizeof(a[0]), cudaMemcpyHostToDevice);
  CHKCUDAERR(err);
  cusparseStatus_t cerr = CUSPARSE_STATUS_SUCCESS;
  cerr = cusparseCreateMatDescr(&matDescr);
  CHKCUSPARSEERR(cerr);
  cerr = cusparseSetMatIndexBase(matDescr, CUSPARSE_INDEX_BASE_ZERO);
  CHKCUSPARSEERR(cerr);
  cerr = cusparseSetMatType(matDescr, CUSPARSE_MATRIX_TYPE_GENERAL);
  CHKCUSPARSEERR(cerr);
  cerr = cusparseCreateHybMat(&localMatrix);
  CHKCUSPARSEERR(cerr);
  cerr = cusparseDcsr2hyb(handle, A.localNumberOfRows, A.localNumberOfColumns,
                          matDescr, a_d, i_d, j_d, localMatrix, 27,
                          CUSPARSE_HYB_PARTITION_USER);
  CHKCUSPARSEERR(cerr);

  // Set up the GS data.
  gelusStatus_t gerr = GELUS_STATUS_SUCCESS;
  gelusSolveDescription_t solveDescr;
  gerr = gelusCreateSolveDescr(&solveDescr);
  CHKGELUSERR(gerr);
  gerr = gelusSetSolveOperation(solveDescr, GELUS_OPERATION_NON_TRANSPOSE);
  CHKGELUSERR(gerr);
  gerr = gelusSetSolveFillMode(solveDescr, GELUS_FILL_MODE_FULL);
  CHKGELUSERR(gerr);
  gerr = gelusSetSolveStorageFormat(solveDescr, GELUS_STORAGE_FORMAT_HYB);
  CHKGELUSERR(gerr);
  gerr = gelusSetOptimizationLevel(solveDescr, GELUS_OPTIMIZATION_LEVEL_THREE);
  CHKGELUSERR(gerr);

  gerr = cugelusCreateSorIterationData(&gsContext);
  CHKGELUSERR(gerr);

#ifdef HPCG_DEBUG
  std::cout << A.localNumberOfRows << std::endl;
  std::cout << A.localNumberOfColumns << std::endl;
  std::cout << A.localNumberOfNonzeros << std::endl;
  int myrank;
  MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
  if (myrank == 0) {
    dumpMatrix(std::cout, i, j, a);
  }
#endif

  gerr = cugelusDcsrsor_iteration_analysis(
      A.localNumberOfRows, solveDescr, GELUS_SOR_SYMMETRIC, 1.0,
      &i[0], &j[0], &a[0], gsContext);
  gerr = gelusDestroySolveDescr(solveDescr);
  CHKGELUSERR(gerr);

  if (A.mgData) {
    err =
      cudaMalloc((void**)&f2c, A.mgData->rc->localLength * sizeof(local_int_t));
    CHKCUDAERR(err);
    err = cudaMemcpy(f2c, A.mgData->f2cOperator,
        A.mgData->rc->localLength * sizeof(local_int_t),
        cudaMemcpyHostToDevice);
    CHKCUDAERR(err);
  }

  err = cudaMalloc((void**)&workvector, A.localNumberOfRows * sizeof(double));
  CHKCUDAERR(err);

  return (int)cerr | (int)gerr | (int)err;
}

int MatrixOptimizationDataTx::ComputeSPMV(const SparseMatrix& A, Vector& x,
    Vector& y, bool copyIn,
    bool copyOut) {
  double* x_dev = 0;
  double* y_dev = 0;
#ifndef HPCG_NOMPI
  DataTransfer transfer = BeginExchangeHalo(A, x);
  EndExchangeHalo(A, x, transfer);
  x_dev = transferDataToGPU(x);
#endif
  if (copyIn) {
#ifdef HPCG_NOMPI
    x_dev = transferDataToGPU(x);
#endif
    y_dev = transferDataToGPU(y);
  } else {
    x_dev = ((VectorOptimizationDataTx*)x.optimizationData)->devicePtr;
    y_dev = ((VectorOptimizationDataTx*)y.optimizationData)->devicePtr;
  }
  double alpha = 1.0;
  double beta = 0.0;
  cusparseStatus_t cerr;
  cerr = cusparseDhybmv(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, &alpha,
      matDescr, localMatrix, x_dev, &beta, y_dev);
  CHKCUSPARSEERR(cerr);
  if (copyOut) {
    transferDataFromGPU(y);
  }
  return 0;
}

int MatrixOptimizationDataTx::ComputeSYMGS(const SparseMatrix &A,
                                           const Vector &r, Vector &x,
                                           int numberOfSmootherSteps,
                                           bool copyIn, bool copyOut) {
  const double* r_dev = 0;
  double* x_dev = 0;
#ifndef HPCG_NOMPI
  DataTransfer transfer = BeginExchangeHalo(A, x);
  EndExchangeHalo(A, x, transfer);
  x_dev = transferDataToGPU(x);
#endif
  if (copyIn) {
#ifdef HPCG_NOMPI
    x_dev = transferDataToGPU(x);
#endif
    r_dev = transferDataToGPU(r);
  } else {
    x_dev = ((VectorOptimizationDataTx*)x.optimizationData)->devicePtr;
    r_dev = ((VectorOptimizationDataTx*)r.optimizationData)->devicePtr;
  }
  launchDeviceCopy(workvector, r_dev, r.localLength);
  scatterFromHalo.spmv(x_dev, workvector, -1, 1);
  gelusStatus_t err =
      cugelusDcsrsor_iterate(x_dev, workvector, GELUS_SOR_INITIAL_GUESS_NONZERO,
                             numberOfSmootherSteps, gsContext);
  CHKGELUSERR(err);
  if (copyOut) {
    transferDataFromGPU(x);
    transferDataFromGPU(r);
  }
  return 0;
}

int MatrixOptimizationDataTx::ComputeProlongation(const SparseMatrix& Af,
    Vector& xf, bool copyIn, bool copyOut) {
  double* xf_d = 0;
  double* xc_d = 0;
  if (copyIn) {
    xf_d = transferDataToGPU(xf);
    xc_d = transferDataToGPU(*Af.mgData->xc);
  } else {
    xf_d = ((VectorOptimizationDataTx*)xf.optimizationData)->devicePtr;
    xc_d = ((VectorOptimizationDataTx*)Af.mgData->xc->optimizationData)->devicePtr;
  }

  local_int_t nc = Af.mgData->rc->localLength;
  launchProlongationKernel(xf_d, xc_d, nc, f2c);

  if (copyOut) {
    transferDataFromGPU(xf);
    transferDataFromGPU(*Af.mgData->xc);
  }
  return 0;
}

int MatrixOptimizationDataTx::ComputeRestriction(const SparseMatrix& Af,
                                                 const Vector& rf, bool copyIn,
                                                 bool copyOut) {
  double* Axf_d = 0;
  double* rf_d = 0;
  double* rc_d = 0;
  if (copyIn) {
    Axf_d = transferDataToGPU(*Af.mgData->Axf);
    rf_d = transferDataToGPU(rf);
    rc_d = transferDataToGPU(*Af.mgData->rc);
  } else {
    Axf_d = ((VectorOptimizationDataTx*)Af.mgData->Axf->optimizationData)->devicePtr;
    rf_d = ((VectorOptimizationDataTx*)rf.optimizationData)->devicePtr;
    rc_d = ((VectorOptimizationDataTx*)Af.mgData->rc->optimizationData)->devicePtr;
  }

  local_int_t nc = Af.mgData->rc->localLength;
  launchRestrictionKernel(rc_d, rf_d, Axf_d, nc, f2c);

  if (copyOut) {
    transferDataFromGPU(*Af.mgData->Axf);
    transferDataFromGPU(rf);
    transferDataFromGPU(*Af.mgData->rc);
  }
  return 0;
}

void dumpMatrix(std::ostream& s, const std::vector<int>& i,
    const std::vector<int>& j, const std::vector<double>& a)
{
  s << "%%MatrixMarket matrix coordinate real general\n";
  int numRows = i.size() - 1;
  int nnz = j.size();
  s << numRows << " " << numRows << " " << nnz << "\n";
  for (int m = 0; m < numRows; ++m) {
    for (int n = i[m]; n < i[m + 1]; ++n) {
      s << m + 1 << " " << j[n] + 1 << " " << a[n] << "\n";
    }
  }
}
<|endoftext|>


<commit_before>// Copyright (C) 2014 Jérôme Leclercq
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Graphics/Graphics.hpp>
#include <Nazara/Core/CallOnExit.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Log.hpp>
#include <Nazara/Graphics/Config.hpp>
#include <Nazara/Graphics/DeferredRenderTechnique.hpp>
#include <Nazara/Graphics/ForwardRenderTechnique.hpp>
#include <Nazara/Graphics/GuillotineTextureAtlas.hpp>
#include <Nazara/Graphics/Material.hpp>
#include <Nazara/Graphics/RenderTechniques.hpp>
#include <Nazara/Graphics/SkinningManager.hpp>
#include <Nazara/Graphics/Loaders/Mesh.hpp>
#include <Nazara/Graphics/Loaders/OBJ.hpp>
#include <Nazara/Graphics/Loaders/Texture.hpp>
#include <Nazara/Renderer/Renderer.hpp>
#include <Nazara/Graphics/Debug.hpp>

bool NzGraphics::Initialize()
{
	if (s_moduleReferenceCounter > 0)
	{
		s_moduleReferenceCounter++;
		return true; // Déjà initialisé
	}

	// Initialisation des dépendances
	if (!NzRenderer::Initialize())
	{
		NazaraError("Failed to initialize Renderer module");
		return false;
	}

	s_moduleReferenceCounter++;

	// Initialisation du module
	NzCallOnExit onExit(NzGraphics::Uninitialize);

	if (!NzMaterial::Initialize())
	{
		NazaraError("Failed to initialize materials");
		return false;
	}

	if (!NzSkinningManager::Initialize())
	{
		NazaraError("Failed to initialize skinning manager");
		return false;
	}

	// Loaders
	NzLoaders_OBJ_Register();

	// Loaders génériques
	NzLoaders_Mesh_Register();
	NzLoaders_Texture_Register();

	// RenderTechniques
	NzRenderTechniques::Register(NzRenderTechniques::ToString(nzRenderTechniqueType_BasicForward), 0, []() -> NzAbstractRenderTechnique* { return new NzForwardRenderTechnique; });

	if (NzDeferredRenderTechnique::IsSupported())
	{
		NzDeferredRenderTechnique::Initialize();
		NzRenderTechniques::Register(NzRenderTechniques::ToString(nzRenderTechniqueType_DeferredShading), 20, []() -> NzAbstractRenderTechnique* { return new NzDeferredRenderTechnique; });
	}

	NzFont::SetDefaultAtlas(new NzGuillotineTextureAtlas);

	onExit.Reset();

	NazaraNotice("Initialized: Graphics module");
	return true;
}

bool NzGraphics::IsInitialized()
{
	return s_moduleReferenceCounter != 0;
}

void NzGraphics::Uninitialize()
{
	if (s_moduleReferenceCounter != 1)
	{
		// Le module est soit encore utilisé, soit pas initialisé
		if (s_moduleReferenceCounter > 1)
			s_moduleReferenceCounter--;

		return;
	}

	// Libération du module
	s_moduleReferenceCounter = 0;

	// Loaders
	NzLoaders_Mesh_Unregister();
	NzLoaders_OBJ_Unregister();
	NzLoaders_Texture_Unregister();

	NzDeferredRenderTechnique::Uninitialize();
	NzMaterial::Uninitialize();
	NzSkinningManager::Uninitialize();

	NazaraNotice("Uninitialized: Graphics module");

	// Libération des dépendances
	NzRenderer::Uninitialize();
}

unsigned int NzGraphics::s_moduleReferenceCounter = 0;
<commit_msg>Fixed missing include<commit_after>// Copyright (C) 2014 Jérôme Leclercq
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Graphics/Graphics.hpp>
#include <Nazara/Core/CallOnExit.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Log.hpp>
#include <Nazara/Graphics/Config.hpp>
#include <Nazara/Graphics/DeferredRenderTechnique.hpp>
#include <Nazara/Graphics/ForwardRenderTechnique.hpp>
#include <Nazara/Graphics/GuillotineTextureAtlas.hpp>
#include <Nazara/Graphics/Material.hpp>
#include <Nazara/Graphics/RenderTechniques.hpp>
#include <Nazara/Graphics/SkinningManager.hpp>
#include <Nazara/Graphics/Loaders/Mesh.hpp>
#include <Nazara/Graphics/Loaders/OBJ.hpp>
#include <Nazara/Graphics/Loaders/Texture.hpp>
#include <Nazara/Renderer/Renderer.hpp>
#include <Nazara/Utility/Font.hpp>
#include <Nazara/Graphics/Debug.hpp>

bool NzGraphics::Initialize()
{
	if (s_moduleReferenceCounter > 0)
	{
		s_moduleReferenceCounter++;
		return true; // Déjà initialisé
	}

	// Initialisation des dépendances
	if (!NzRenderer::Initialize())
	{
		NazaraError("Failed to initialize Renderer module");
		return false;
	}

	s_moduleReferenceCounter++;

	// Initialisation du module
	NzCallOnExit onExit(NzGraphics::Uninitialize);

	if (!NzMaterial::Initialize())
	{
		NazaraError("Failed to initialize materials");
		return false;
	}

	if (!NzSkinningManager::Initialize())
	{
		NazaraError("Failed to initialize skinning manager");
		return false;
	}

	// Loaders
	NzLoaders_OBJ_Register();

	// Loaders génériques
	NzLoaders_Mesh_Register();
	NzLoaders_Texture_Register();

	// RenderTechniques
	NzRenderTechniques::Register(NzRenderTechniques::ToString(nzRenderTechniqueType_BasicForward), 0, []() -> NzAbstractRenderTechnique* { return new NzForwardRenderTechnique; });

	if (NzDeferredRenderTechnique::IsSupported())
	{
		NzDeferredRenderTechnique::Initialize();
		NzRenderTechniques::Register(NzRenderTechniques::ToString(nzRenderTechniqueType_DeferredShading), 20, []() -> NzAbstractRenderTechnique* { return new NzDeferredRenderTechnique; });
	}

	NzFont::SetDefaultAtlas(new NzGuillotineTextureAtlas);

	onExit.Reset();

	NazaraNotice("Initialized: Graphics module");
	return true;
}

bool NzGraphics::IsInitialized()
{
	return s_moduleReferenceCounter != 0;
}

void NzGraphics::Uninitialize()
{
	if (s_moduleReferenceCounter != 1)
	{
		// Le module est soit encore utilisé, soit pas initialisé
		if (s_moduleReferenceCounter > 1)
			s_moduleReferenceCounter--;

		return;
	}

	// Libération du module
	s_moduleReferenceCounter = 0;

	// Loaders
	NzLoaders_Mesh_Unregister();
	NzLoaders_OBJ_Unregister();
	NzLoaders_Texture_Unregister();

	NzDeferredRenderTechnique::Uninitialize();
	NzMaterial::Uninitialize();
	NzSkinningManager::Uninitialize();

	NazaraNotice("Uninitialized: Graphics module");

	// Libération des dépendances
	NzRenderer::Uninitialize();
}

unsigned int NzGraphics::s_moduleReferenceCounter = 0;
<|endoftext|>