<commit_before>enum AlgoType {kKT, kANTIKT};
enum JetType  {kFULLJETS, kCHARGEDJETS, kNEUTRALJETS};

AliAnalysisTaskEmcalJetTriggerQA* AddTaskEmcalJetTriggerQA(TString     kTracksName         = "PicoTracks",
							   TString     kClusName           = "caloClustersCorr",
							   Double_t    R                   = 0.4,
							   Double_t    ptminTrack          = 0.15,
							   Double_t    etminClus           = 0.3,
							   Int_t       rhoType             = 0,
							   TString     trigClass           = "",
							   TString     kEmcalCellsName     = "",
							   const char *CentEst             = "V0A",
							   Int_t       pSel                = AliVEvent::kINT7,
							   Float_t     nefCut              = 10.,
							   TString     kEmcalTriggers      = "",
							   TString     kPeriod             = "LHC13b"
							   ) {

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
    {
      Error("AddTaskEmcalJetTriggerQA","No analysis manager found.");
      return 0;
    }
  Bool_t ismc=kFALSE;
  ismc = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE;

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler())
    {
      ::Error("AddTaskEmcalJetTriggerQA", "This task requires an input event handler");
      return NULL;
    }

  // #### Add necessary jet finder tasks
  gROOT->LoadMacro("$ALICE_ROOT/PWGJE/EMCALJetTasks/macros/AddTaskEmcalJet.C");

  AliEmcalJetTask* jetFinderTask1;
  AliEmcalJetTask* jetFinderTask2;
  if(kClusName.IsNull()) {  //particle level jets
    jetFinderTask1 = AddTaskEmcalJet(kTracksName, "", kANTIKT, R, kFULLJETS, ptminTrack, etminClus);
    jetFinderTask2 = AddTaskEmcalJet(kTracksName, "", kANTIKT, R, kCHARGEDJETS, ptminTrack, etminClus);
  }
  else if(kTracksName.IsNull()) { //neutral/calo jets
    jetFinderTask1 = AddTaskEmcalJet(kTracksName, kClusName, kANTIKT, R, kNEUTRALJETS, ptminTrack, etminClus);
    jetFinderTask2 = AddTaskEmcalJet(kTracksName, kClusName, kANTIKT, R, kFULLJETS, ptminTrack, etminClus);
  }
  else { //full jets
    jetFinderTask1 = AddTaskEmcalJet(kTracksName, kClusName, kANTIKT, R, kFULLJETS, ptminTrack, etminClus);
    jetFinderTask2 = AddTaskEmcalJet(kTracksName, kClusName, kANTIKT, R, kCHARGEDJETS, ptminTrack, etminClus);
  }
  jetFinderTask1->SelectCollisionCandidates(AliVEvent::kAny);
  jetFinderTask2->SelectCollisionCandidates(AliVEvent::kAny);

  TString strJets1 = jetFinderTask1->GetName();
  TString strJets2 = jetFinderTask2->GetName();

  AliAnalysisTaskRhoBase *rhoTask;
  if(rhoType==1) {
    rhoTask = AttachRhoTask(kPeriod,kTracksName,kClusName,R,ptminTrack,etminClus);
    if(rhoTask) {
      rhoTask->SetCentralityEstimator(CentEst);
      rhoTask->SelectCollisionCandidates(AliVEvent::kAny);
    }
    else {
      Warning("AddTaskEmcalJetTriggerQA","Asked for rho task but configuration unknown. Continuing configuration without rho task.");
      rhoType = 0;
    }
  }

  TString wagonName = Form("TriggerQA_%s_%s_TC%s",strJets1.Data(),strJets2.Data(),trigClass.Data());

  //Configure TriggerQA task
  AliAnalysisTaskEmcalJetTriggerQA *task = new AliAnalysisTaskEmcalJetTriggerQA(wagonName);
  AliParticleContainer *trackCont  = task->AddParticleContainer(kTracksName.Data());
  AliClusterContainer *clusterCont = task->AddClusterContainer(kClusName.Data());

  task->SetContainerFull(0);
  task->SetContainerCharged(1);
  AliJetContainer *jetCont0 = task->AddJetContainer(strJets1.Data(),"EMCAL",R);
  if(rhoType==1) task->SetRhoName(rhoTask->GetOutRhoScaledName(),0);
  AliJetContainer *jetCont1 = NULL;
  if(strJets2.Contains("Charged")) {
    jetCont1 = task->AddJetContainer(strJets2.Data(),"TPC",R);
    if(rhoType==1) task->SetRhoName(rhoTask->GetOutRhoName(),1);
  }
  else {
    jetCont1 = task->AddJetContainer(strJets2.Data(),"EMCAL",R);
    task->SetZLeadingCut(0.98,0.98,1);
    task->SetNEFCut(0.,nefCut,1);
  }

  task->SetZLeadingCut(0.98,0.98,0);
  task->SetNEFCut(0.,nefCut,0);

  for(Int_t i=0; i<2; i++) {
    task->SetPercAreaCut(0.6, i);
  }

  task->SetTriggerClass(trigClass.Data());
  task->SetCaloCellsName(kEmcalCellsName.Data());
  task->SetCaloTriggerPatchInfoName(kEmcalTriggers.Data());

  task->SetCentralityEstimator(CentEst);
  task->SelectCollisionCandidates(pSel);

  task->SetUseAliAnaUtils(kTRUE);
  task->SetVzRange(-10.,10.);

  if(kPeriod.Contains("LHC13b4"))
    task-SetIsPythia(kTRUE);

  mgr->AddTask(task);

  //Connnect input
  mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer() );

  //Connect output
  AliAnalysisDataContainer *coutput1 = 0x0;
  TString containerName1 = Form("%s",wagonName.Data());
  TString outputfile = Form("%s:%s",AliAnalysisManager::GetCommonFileName(),wagonName.Data());
  coutput1 = mgr->CreateContainer(containerName1, TList::Class(),AliAnalysisManager::kOutputContainer,outputfile);
  mgr->ConnectOutput(task,1,coutput1);

  return task;
}

AliAnalysisTaskRhoBase *AttachRhoTask(TString     kPeriod             = "LHC13b",
				      TString     kTracksName         = "PicoTracks",
				      TString     kClusName           = "caloClustersCorr",
				      Double_t    R                   = 0.4,
				      Double_t    ptminTrack          = 0.15,
				      Double_t    etminClus           = 0.3
				      ) {

  AliAnalysisTaskRhoBase *rhoTaskBase;

  kPeriod.ToLower();

  // Add kt jet finder and rho task in case we want background subtraction
  AliEmcalJetTask *jetFinderKt;
  AliEmcalJetTask *jetFinderAKt;
  jetFinderKt   = AddTaskEmcalJet(kTracksName, kClusName, kKT, R, kCHARGEDJETS, ptminTrack, etminClus);
  jetFinderAKt  = AddTaskEmcalJet(kTracksName, kClusName, kANTIKT, R, kCHARGEDJETS, ptminTrack, etminClus);
  jetFinderKt->SelectCollisionCandidates(AliVEvent::kAny);
  jetFinderAKt->SelectCollisionCandidates(AliVEvent::kAny);

  if(kPeriod.EqualTo("lhc13b") || kPeriod.EqualTo("lhc13c") || kPeriod.EqualTo("lhc13d") || kPeriod.EqualTo("lhc13e") || kPeriod.EqualTo("lhc13f")) {
    jetFinderKt->SetMinJetPt(0.);

    gROOT->LoadMacro("$ALICE_ROOT/PWGJE/EMCALJetTasks/macros/AddTaskRhoSparse.C");
    TF1 *fScale = new TF1("fScale","1.42",0.,100.); //scale factor for pPb
    AliAnalysisTaskRhoSparse *rhoTaskSparse = AddTaskRhoSparse(
			       jetFinderKt->GetName(),
			       jetFinderAKt->GetName(),
			       kTracksName,
			       kClusName,
			       Form("RhoSparseR%03d",(int)(100*R)),
			       R,
			       "TPC",
			       0.01,
			       0.15,
			       0,
			       fScale,
			       0,
			       kTRUE,
			       Form("RhoSparseR%03d",(int)(100*R)),
			       kTRUE
			       );
    rhoTaskSparse->SetUseAliAnaUtils(kTRUE);
    rhoTaskBase = dynamic_cast<AliAnalysisTaskRhoBase*>rhoTaskSparse;
  }
  else if(kPeriod.EqualTo("lhc10h") || kPeriod.EqualTo("lhc11h") ) {
    gROOT->LoadMacro("$ALICE_ROOT/PWGJE/EMCALJetTasks/macros/AddTaskRho.C");

    TF1* sfunc = new TF1("sfunc","[0]*x*x+[1]*x+[2]",-1,100);
    sfunc->SetParameter(2,1.76458);
    sfunc->SetParameter(1,-0.0111656);
    sfunc->SetParameter(0,0.000107296);
    AliAnalysisTaskRho *rhoTask = AddTaskRho(
					     jetFinderKt->GetName(),
					     kTracksName,
					     kClusName,
					     Form("RhoR%03d",(int)(100*R)),
					     R,
					     "TPC",
					     0.01,
					     0,
					     sfunc,
					     2,
					     kTRUE);
    rhoTask->SetHistoBins(100,0,250);

    rhoTaskBase = dynamic_cast<AliAnalysisTaskRhoBase*>rhoTask;
  }

  return rhoTaskBase;
}
<commit_msg>Introduced Beamtype variable in AddTaskEmcalJetTriggerQA<commit_after>enum AlgoType {kKT, kANTIKT};
enum JetType  {kFULLJETS, kCHARGEDJETS, kNEUTRALJETS};

AliAnalysisTaskEmcalJetTriggerQA* AddTaskEmcalJetTriggerQA(TString     kTracksName         = "PicoTracks",
							   TString     kClusName           = "caloClustersCorr",
							   Double_t    R                   = 0.4,
							   Double_t    ptminTrack          = 0.15,
							   Double_t    etminClus           = 0.3,
							   Int_t       rhoType             = 0,
							   TString     trigClass           = "",
							   TString     kEmcalCellsName     = "",
							   const char *CentEst             = "V0A",
							   Int_t       pSel                = AliVEvent::kINT7,
							   Float_t     nefCut              = 10.,
							   TString     kEmcalTriggers      = "",
							   TString     kPeriod             = "LHC13b",
                                                           TString     kBeamType           = "pp" //or pPb or PbPb
							   ) {
  // The following three lines are added for backwards compatibility
  kPeriod.ToLower();
  if(kPeriod.EqualTo("lhc10h") || kPeriod.EqualTo("lhc11h")) kBeamType = "PbPb";
  if(kPeriod.EqualTo("lhc13b") || kPeriod.EqualTo("lhc13c") || kPeriod.EqualTo("lhc13d") || kPeriod.EqualTo("lhc13e") || kPeriod.EqualTo("lhc13f")) kBeamType = "pPb";

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
    {
      Error("AddTaskEmcalJetTriggerQA","No analysis manager found.");
      return 0;
    }
  Bool_t ismc=kFALSE;
  ismc = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE;

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler())
    {
      ::Error("AddTaskEmcalJetTriggerQA", "This task requires an input event handler");
      return NULL;
    }

  // #### Add necessary jet finder tasks
  gROOT->LoadMacro("$ALICE_ROOT/PWGJE/EMCALJetTasks/macros/AddTaskEmcalJet.C");

  AliEmcalJetTask* jetFinderTask1;
  AliEmcalJetTask* jetFinderTask2;
  if(kClusName.IsNull()) {  //particle level jets
    jetFinderTask1 = AddTaskEmcalJet(kTracksName, "", kANTIKT, R, kFULLJETS, ptminTrack, etminClus);
    jetFinderTask2 = AddTaskEmcalJet(kTracksName, "", kANTIKT, R, kCHARGEDJETS, ptminTrack, etminClus);
  }
  else if(kTracksName.IsNull()) { //neutral/calo jets
    jetFinderTask1 = AddTaskEmcalJet(kTracksName, kClusName, kANTIKT, R, kNEUTRALJETS, ptminTrack, etminClus);
    jetFinderTask2 = AddTaskEmcalJet(kTracksName, kClusName, kANTIKT, R, kFULLJETS, ptminTrack, etminClus);
  }
  else { //full jets
    jetFinderTask1 = AddTaskEmcalJet(kTracksName, kClusName, kANTIKT, R, kFULLJETS, ptminTrack, etminClus);
    jetFinderTask2 = AddTaskEmcalJet(kTracksName, kClusName, kANTIKT, R, kCHARGEDJETS, ptminTrack, etminClus);
  }
  jetFinderTask1->SelectCollisionCandidates(AliVEvent::kAny);
  jetFinderTask2->SelectCollisionCandidates(AliVEvent::kAny);

  TString strJets1 = jetFinderTask1->GetName();
  TString strJets2 = jetFinderTask2->GetName();

  AliAnalysisTaskRhoBase *rhoTask;
  if(rhoType==1) {
    rhoTask = AttachRhoTask(kBeamType,kTracksName,kClusName,R,ptminTrack,etminClus);
    if(rhoTask) {
      rhoTask->SetCentralityEstimator(CentEst);
      rhoTask->SelectCollisionCandidates(AliVEvent::kAny);
    }
    else {
      Warning("AddTaskEmcalJetTriggerQA","Asked for rho task but configuration unknown. Continuing configuration without rho task.");
      rhoType = 0;
    }
  }

  TString wagonName = Form("TriggerQA_%s_%s_TC%s",strJets1.Data(),strJets2.Data(),trigClass.Data());

  //Configure TriggerQA task
  AliAnalysisTaskEmcalJetTriggerQA *task = new AliAnalysisTaskEmcalJetTriggerQA(wagonName);
  AliParticleContainer *trackCont  = task->AddParticleContainer(kTracksName.Data());
  AliClusterContainer *clusterCont = task->AddClusterContainer(kClusName.Data());

  task->SetContainerFull(0);
  task->SetContainerCharged(1);
  AliJetContainer *jetCont0 = task->AddJetContainer(strJets1.Data(),"EMCAL",R);
  if(rhoType==1) task->SetRhoName(rhoTask->GetOutRhoScaledName(),0);
  AliJetContainer *jetCont1 = NULL;
  if(strJets2.Contains("Charged")) {
    jetCont1 = task->AddJetContainer(strJets2.Data(),"TPC",R);
    if(rhoType==1) task->SetRhoName(rhoTask->GetOutRhoName(),1);
  }
  else {
    jetCont1 = task->AddJetContainer(strJets2.Data(),"EMCAL",R);
    task->SetZLeadingCut(0.98,0.98,1);
    task->SetNEFCut(0.,nefCut,1);
  }

  task->SetZLeadingCut(0.98,0.98,0);
  task->SetNEFCut(0.,nefCut,0);

  for(Int_t i=0; i<2; i++) {
    task->SetPercAreaCut(0.6, i);
  }

  task->SetTriggerClass(trigClass.Data());
  task->SetCaloCellsName(kEmcalCellsName.Data());
  task->SetCaloTriggerPatchInfoName(kEmcalTriggers.Data());

  task->SetCentralityEstimator(CentEst);
  task->SelectCollisionCandidates(pSel);

  task->SetUseAliAnaUtils(kTRUE);
  task->SetVzRange(-10.,10.);

  if(kPeriod.Contains("LHC13b4"))
    task->SetIsPythia(kTRUE);

  mgr->AddTask(task);

  //Connnect input
  mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer() );

  //Connect output
  AliAnalysisDataContainer *coutput1 = 0x0;
  TString containerName1 = Form("%s",wagonName.Data());
  TString outputfile = Form("%s:%s",AliAnalysisManager::GetCommonFileName(),wagonName.Data());
  coutput1 = mgr->CreateContainer(containerName1, TList::Class(),AliAnalysisManager::kOutputContainer,outputfile);
  mgr->ConnectOutput(task,1,coutput1);

  return task;
}

AliAnalysisTaskRhoBase *AttachRhoTask(TString     kBeamType           = "pp",
				      TString     kTracksName         = "PicoTracks",
				      TString     kClusName           = "caloClustersCorr",
				      Double_t    R                   = 0.4,
				      Double_t    ptminTrack          = 0.15,
				      Double_t    etminClus           = 0.3
				      ) {

  AliAnalysisTaskRhoBase *rhoTaskBase;

  // Add kt jet finder and rho task in case we want background subtraction
  AliEmcalJetTask *jetFinderKt;
  AliEmcalJetTask *jetFinderAKt;
  jetFinderKt   = AddTaskEmcalJet(kTracksName, kClusName, kKT, R, kCHARGEDJETS, ptminTrack, etminClus);
  jetFinderAKt  = AddTaskEmcalJet(kTracksName, kClusName, kANTIKT, R, kCHARGEDJETS, ptminTrack, etminClus);
  jetFinderKt->SelectCollisionCandidates(AliVEvent::kAny);
  jetFinderAKt->SelectCollisionCandidates(AliVEvent::kAny);

  if(kBeamType == "pPb") {
    jetFinderKt->SetMinJetPt(0.);

    gROOT->LoadMacro("$ALICE_ROOT/PWGJE/EMCALJetTasks/macros/AddTaskRhoSparse.C");
    TF1 *fScale = new TF1("fScale","1.42",0.,100.); //scale factor for pPb
    AliAnalysisTaskRhoSparse *rhoTaskSparse = AddTaskRhoSparse(
			       jetFinderKt->GetName(),
			       jetFinderAKt->GetName(),
			       kTracksName,
			       kClusName,
			       Form("RhoSparseR%03d",(int)(100*R)),
			       R,
			       "TPC",
			       0.01,
			       0.15,
			       0,
			       fScale,
			       0,
			       kTRUE,
			       Form("RhoSparseR%03d",(int)(100*R)),
			       kTRUE
			       );
    rhoTaskSparse->SetUseAliAnaUtils(kTRUE);
    rhoTaskBase = dynamic_cast<AliAnalysisTaskRhoBase*>rhoTaskSparse;
  }
  else if(kBeamType=="PbPb") {
    gROOT->LoadMacro("$ALICE_ROOT/PWGJE/EMCALJetTasks/macros/AddTaskRho.C");

    TF1* sfunc = new TF1("sfunc","[0]*x*x+[1]*x+[2]",-1,100);
    sfunc->SetParameter(2,1.76458);
    sfunc->SetParameter(1,-0.0111656);
    sfunc->SetParameter(0,0.000107296);
    AliAnalysisTaskRho *rhoTask = AddTaskRho(
					     jetFinderKt->GetName(),
					     kTracksName,
					     kClusName,
					     Form("RhoR%03d",(int)(100*R)),
					     R,
					     "TPC",
					     0.01,
					     0,
					     sfunc,
					     2,
					     kTRUE);
    rhoTask->SetHistoBins(100,0,250);

    rhoTaskBase = dynamic_cast<AliAnalysisTaskRhoBase*>rhoTask;
  }

  return rhoTaskBase;
}
<|endoftext|>


<commit_before>/*
  Last update: 26/03/2012, vzero branch, in PbPb macro execute the vzero code, a bug was fixed
*/

AliAnalysisTask* AddTask(Bool_t AnalysisMC, const Char_t* taskname, Int_t typerun, UInt_t kTriggerInt, Float_t minc, Float_t maxc)
{
  // Creates a pid task and adds it to the analysis manager

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

  // Check the analysis type using the event handlers connected to the
  // analysis manager The availability of MC handler can also be
  // checked here.
  // =========================================================================
  if (!mgr->GetInputEventHandler()) {
    Error("AddTaskHighPtDeDx", "This task requires an input event handler");
    return NULL;
  }

  //
  // Add track filters, with Golden Cuts
  //
  /*
  AliAnalysisFilter* trackFilterGolden = new AliAnalysisFilter("trackFilter");
  AliESDtrackCuts* esdTrackCutsGolden =
    AliESDtrackCuts::GetStandardITSTPCTrackCuts2010(kTRUE);
  trackFilterGolden->AddCuts(esdTrackCutsGolden);
  */

  AliAnalysisFilter* trackFilterGolden = new AliAnalysisFilter("trackFilter");
  AliESDtrackCuts* esdTrackCutsGolden = AliESDtrackCuts::GetStandardITSTPCTrackCuts2010(kTRUE,1);
  esdTrackCutsGolden->SetMinNCrossedRowsTPC(120);
  esdTrackCutsGolden->SetMinRatioCrossedRowsOverFindableClustersTPC(0.8);
  esdTrackCutsGolden->SetMaxChi2PerClusterITS(36);
  esdTrackCutsGolden->SetMaxFractionSharedTPCClusters(0.4);
  esdTrackCutsGolden->SetMaxChi2TPCConstrainedGlobal(36);
  esdTrackCutsGolden->SetMaxDCAToVertexXY(3.0);

  trackFilterGolden->AddCuts(esdTrackCutsGolden);

  //old cuts without golden cut
  AliAnalysisFilter* trackFilter0 = new AliAnalysisFilter("trackFilter");
  Bool_t clusterCut=0;
  Bool_t selPrimaries=kTRUE;
  AliESDtrackCuts* esdTrackCutsL0 = new AliESDtrackCuts;
 // TPC
  if(clusterCut == 0)  esdTrackCutsL0->SetMinNClustersTPC(70);
  else if (clusterCut == 1) {
    esdTrackCutsL0->SetMinNCrossedRowsTPC(70);
    esdTrackCutsL0->SetMinRatioCrossedRowsOverFindableClustersTPC(0.8);
  }
  else {
    AliWarningClass(Form("Wrong value of the clusterCut parameter (%d), using cut on Nclusters",clusterCut));
    esdTrackCutsL0->SetMinNClustersTPC(70);
  }
  esdTrackCutsL0->SetMaxChi2PerClusterTPC(4);
  esdTrackCutsL0->SetAcceptKinkDaughters(kFALSE);
  esdTrackCutsL0->SetRequireTPCRefit(kTRUE);
  // ITS
  esdTrackCutsL0->SetRequireITSRefit(kTRUE);
  esdTrackCutsL0->SetClusterRequirementITS(AliESDtrackCuts::kSPD,
					 AliESDtrackCuts::kAny);
  if(selPrimaries) {
    // 7*(0.0026+0.0050/pt^1.01)
    esdTrackCutsL0->SetMaxDCAToVertexXYPtDep("0.0182+0.0350/pt^1.01");
  }
  esdTrackCutsL0->SetMaxDCAToVertexZ(2);
  esdTrackCutsL0->SetDCAToVertex2D(kFALSE);
  esdTrackCutsL0->SetRequireSigmaToVertex(kFALSE);
  esdTrackCutsL0->SetMaxChi2PerClusterITS(1e10);
  esdTrackCutsL0->SetMaxChi2TPCConstrainedGlobal(1e10);

  trackFilter0->AddCuts(esdTrackCutsL0);

  AliAnalysisFilter* trackFilterTPC = new AliAnalysisFilter("trackFilterTPC");
  AliESDtrackCuts* esdTrackCutsTPC =
    AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
  trackFilterTPC->AddCuts(esdTrackCutsTPC);

  // Create the task and configure it
  //========================================================================
  if(typerun==2){//heavy ion analysis

    const Int_t nCent = 1;
    //    AliAnalysisTaskHighPtDeDx* taskHighPtDeDx[6];
    AliAnalysisTaskHighPtDeDx* taskHighPtDeDx[nCent];
    //    for( Int_t i=0; i<6; ++i ){
    for( Int_t i=0; i<nCent; ++i ){
      taskHighPtDeDx[i]=0;
      Char_t TaskName[256]={0};
      sprintf(TaskName,"%s_%1.0f_%1.0f",taskname,minc,maxc);

      taskHighPtDeDx[i] = new AliAnalysisTaskHighPtDeDx(TaskName);
      TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
      taskHighPtDeDx[i]->SetAnalysisType(type);
      taskHighPtDeDx[i]->SetAnalysisMC(AnalysisMC);
      taskHighPtDeDx[i]->SetAnalysisPbPb(kTRUE);
      taskHighPtDeDx[i]->SetProduceVZEROBranch(kTRUE);
      taskHighPtDeDx[i]->SetProduceTPCBranch(kFALSE);
      taskHighPtDeDx[i]->SetDebugLevel(0);
      taskHighPtDeDx[i]->SetEtaCut(0.8);
      taskHighPtDeDx[i]->SetVtxCut(10.0);
      taskHighPtDeDx[i]->SetMinPt(0.0); // default 2.0
      taskHighPtDeDx[i]->SetLowPtFraction(0.01); // keep 1% of tracks below min pt
      taskHighPtDeDx[i]->SetTreeOption(1);
      taskHighPtDeDx[i]->SetTrigger1(kTriggerInt);
      //      taskHighPtDeDx[i]->SetTrigger2(kTriggerInt[1]);
      taskHighPtDeDx[i]->SetTrigger2(kTriggerInt);
      taskHighPtDeDx[i]->SetMinCent(minc);
      taskHighPtDeDx[i]->SetMaxCent(maxc);
      //Set Filtesr
      taskHighPtDeDx[i]->SetTrackFilterGolden(trackFilterGolden);
      taskHighPtDeDx[i]->SetTrackFilter(trackFilter0);
      taskHighPtDeDx[i]->SetTrackFilterTPC(trackFilterTPC);

      //V0's cuts
      taskHighPtDeDx[i]->SetMassCut(0.1);         // def: 0.03
      taskHighPtDeDx[i]->SetRequireRecV0(kTRUE); // def: kTRUE
      //taskHighPtDeDx[i]->SetStoreMcIn(kFALSE);     // def: kFALSE
      taskHighPtDeDx[i]->SetStoreMcIn(kTRUE);     // def: kFALSE

      mgr->AddTask(taskHighPtDeDx[i]);

    }

    // 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 *cout_hist[nCent];
    for( Int_t i=0; i<nCent; ++i ){

      cout_hist[i]=0;
      Char_t outFileName[256]={0};
      sprintf(outFileName,"%s_Tree_%1.0f_%1.0f.root",taskname,minc,maxc);
      //AliAnalysisDataContainer *cout_hist    = 0;

      cout_hist[i] = mgr->CreateContainer(Form("output_%1.0f_%1.0f",minc,maxc), TList::Class(), AliAnalysisManager::kOutputContainer, outFileName);
      mgr->ConnectInput (taskHighPtDeDx[i], 0, mgr->GetCommonInputContainer());
      mgr->ConnectOutput(taskHighPtDeDx[i], 1, cout_hist[i]);

    }

    // Return task pointer at the end
    return taskHighPtDeDx[0];
  }
  if(typerun==3){//pp analysis

    AliAnalysisTaskHighPtDeDx* taskHighPtDeDx = new AliAnalysisTaskHighPtDeDx("taskHighPtDeDxpp");
    TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
    taskHighPtDeDx->SetAnalysisType(type);
    taskHighPtDeDx->SetAnalysisMC(AnalysisMC);
    taskHighPtDeDx->SetAnalysisPbPb(kFALSE);
    taskHighPtDeDx->SetProduceVZEROBranch(kTRUE);
    taskHighPtDeDx->SetProduceTPCBranch(kFALSE);
    taskHighPtDeDx->SetDebugLevel(0);
    taskHighPtDeDx->SetEtaCut(0.8);
    taskHighPtDeDx->SetVtxCut(10.0);
    taskHighPtDeDx->SetMinPt(0.0); // default 2.0
    taskHighPtDeDx->SetLowPtFraction(0.01); // keep 1% of tracks below min pt
    taskHighPtDeDx->SetTreeOption(1);
    taskHighPtDeDx->SetTrigger1(kTriggerInt);
    //    taskHighPtDeDx->SetTrigger2(kTriggerInt[1]);
    taskHighPtDeDx->SetTrigger2(kTriggerInt);
    //Set Filtesr
    taskHighPtDeDx->SetTrackFilterGolden(trackFilterGolden);
    taskHighPtDeDx->SetTrackFilter(trackFilter0);
    taskHighPtDeDx->SetTrackFilterTPC(trackFilterTPC);
    //V0's cuts
    taskHighPtDeDx->SetMassCut(0.1);         // def: 0.03
    taskHighPtDeDx->SetRequireRecV0(kTRUE); // def: kTRUE
    taskHighPtDeDx->SetStoreMcIn(kFALSE);     // def: kFALSE

    mgr->AddTask(taskHighPtDeDx);

    // 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 *cout_histdedx;

    cout_histdedx=0;
    Char_t outFileName[256]={0};
    sprintf(outFileName,"%s_Tree.root",taskname);
    //AliAnalysisDataContainer *cout_hist    = 0;

    cout_histdedx = mgr->CreateContainer("outputdedx", TList::Class(), AliAnalysisManager::kOutputContainer, outFileName);
    mgr->ConnectInput (taskHighPtDeDx, 0, mgr->GetCommonInputContainer());
    mgr->ConnectOutput(taskHighPtDeDx, 1, cout_histdedx);

    // Return task pointer at the end
    return taskHighPtDeDx;

  }

 if(typerun==4){//pPb analysis
   cout<<"<<<<<<<<<<<<<<<<<<<<<<<<<<                 Runing pPb    <<<<<<<<<<<<<<"<<endl;

    AliAnalysisTaskHighPtDeDx* taskHighPtDeDx = new AliAnalysisTaskHighPtDeDx("taskHighPtDeDxpp");
    TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
    taskHighPtDeDx->SetAnalysisType(type);
    taskHighPtDeDx->SetAnalysisMC(AnalysisMC);
    taskHighPtDeDx->SetAnalysisPbPb(kTRUE);
    taskHighPtDeDx->SetMinCent(-200);
    taskHighPtDeDx->SetMaxCent(200);
    taskHighPtDeDx->SetProduceVZEROBranch(kTRUE);
    taskHighPtDeDx->SetProduceTPCBranch(kFALSE);
    taskHighPtDeDx->SetDebugLevel(0);
    taskHighPtDeDx->SetEtaCut(0.8);
    taskHighPtDeDx->SetVtxCut(10.0);
    taskHighPtDeDx->SetMinPt(0.0); // default 2.0
    taskHighPtDeDx->SetLowPtFraction(0.01); // keep 1% of tracks below min pt
    taskHighPtDeDx->SetTreeOption(1);
    taskHighPtDeDx->SetTrigger1(kTriggerInt);
    //    taskHighPtDeDx->SetTrigger2(kTriggerInt[1]);
    taskHighPtDeDx->SetTrigger2(kTriggerInt);
    //Set Filtesr
    taskHighPtDeDx->SetTrackFilterGolden(trackFilterGolden);
    taskHighPtDeDx->SetTrackFilter(trackFilter0);
    taskHighPtDeDx->SetTrackFilterTPC(trackFilterTPC);
    //V0's cuts
    taskHighPtDeDx->SetMassCut(0.1);         // def: 0.03
    taskHighPtDeDx->SetRequireRecV0(kTRUE); // def: kTRUE
    taskHighPtDeDx->SetStoreMcIn(kTRUE);     // def: kFALSE

    mgr->AddTask(taskHighPtDeDx);

    // 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 *cout_histdedx;

    cout_histdedx=0;
    Char_t outFileName[256]={0};
    sprintf(outFileName,"%s_Tree.root",taskname);
    //AliAnalysisDataContainer *cout_hist    = 0;

    cout_histdedx = mgr->CreateContainer("outputdedx", TList::Class(), AliAnalysisManager::kOutputContainer, outFileName);
    mgr->ConnectInput (taskHighPtDeDx, 0, mgr->GetCommonInputContainer());
    mgr->ConnectOutput(taskHighPtDeDx, 1, cout_histdedx);

    // Return task pointer at the end
    return taskHighPtDeDx;

  }

}
<commit_msg>change output file name to the defined one: AnalysisResults.root instead of IdentifiedHighPt_Tree_0_10.root<commit_after>/*
  Last update:
  17 aug 2015: use common output file name

*/

AliAnalysisTask* AddTask(Bool_t AnalysisMC, const Char_t* taskname, Int_t typerun, UInt_t kTriggerInt, Float_t minc, Float_t maxc)
{

  // Creates a pid task and adds it to the analysis manager

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

  // Check the analysis type using the event handlers connected to the
  // analysis manager The availability of MC handler can also be
  // checked here.
  // =========================================================================
  if (!mgr->GetInputEventHandler()) {
    Error("AddTaskHighPtDeDx", "This task requires an input event handler");
    return NULL;
  }

  //
  // Add track filters, with Golden Cuts
  //
  /*
  AliAnalysisFilter* trackFilterGolden = new AliAnalysisFilter("trackFilter");
  AliESDtrackCuts* esdTrackCutsGolden =
    AliESDtrackCuts::GetStandardITSTPCTrackCuts2010(kTRUE);
  trackFilterGolden->AddCuts(esdTrackCutsGolden);
  */

  AliAnalysisFilter* trackFilterGolden = new AliAnalysisFilter("trackFilter");
  AliESDtrackCuts* esdTrackCutsGolden = AliESDtrackCuts::GetStandardITSTPCTrackCuts2010(kTRUE,1);
  esdTrackCutsGolden->SetMinNCrossedRowsTPC(120);
  esdTrackCutsGolden->SetMinRatioCrossedRowsOverFindableClustersTPC(0.8);
  esdTrackCutsGolden->SetMaxChi2PerClusterITS(36);
  esdTrackCutsGolden->SetMaxFractionSharedTPCClusters(0.4);
  esdTrackCutsGolden->SetMaxChi2TPCConstrainedGlobal(36);
  esdTrackCutsGolden->SetMaxDCAToVertexXY(3.0);

  trackFilterGolden->AddCuts(esdTrackCutsGolden);

  //old cuts without golden cut
  AliAnalysisFilter* trackFilter0 = new AliAnalysisFilter("trackFilter");
  Bool_t clusterCut=0;
  Bool_t selPrimaries=kTRUE;
  AliESDtrackCuts* esdTrackCutsL0 = new AliESDtrackCuts;
 // TPC
  if(clusterCut == 0)  esdTrackCutsL0->SetMinNClustersTPC(70);
  else if (clusterCut == 1) {
    esdTrackCutsL0->SetMinNCrossedRowsTPC(70);
    esdTrackCutsL0->SetMinRatioCrossedRowsOverFindableClustersTPC(0.8);
  }
  else {
    AliWarningClass(Form("Wrong value of the clusterCut parameter (%d), using cut on Nclusters",clusterCut));
    esdTrackCutsL0->SetMinNClustersTPC(70);
  }
  esdTrackCutsL0->SetMaxChi2PerClusterTPC(4);
  esdTrackCutsL0->SetAcceptKinkDaughters(kFALSE);
  esdTrackCutsL0->SetRequireTPCRefit(kTRUE);
  // ITS
  esdTrackCutsL0->SetRequireITSRefit(kTRUE);
  esdTrackCutsL0->SetClusterRequirementITS(AliESDtrackCuts::kSPD,
					 AliESDtrackCuts::kAny);
  if(selPrimaries) {
    // 7*(0.0026+0.0050/pt^1.01)
    esdTrackCutsL0->SetMaxDCAToVertexXYPtDep("0.0182+0.0350/pt^1.01");
  }
  esdTrackCutsL0->SetMaxDCAToVertexZ(2);
  esdTrackCutsL0->SetDCAToVertex2D(kFALSE);
  esdTrackCutsL0->SetRequireSigmaToVertex(kFALSE);
  esdTrackCutsL0->SetMaxChi2PerClusterITS(1e10);
  esdTrackCutsL0->SetMaxChi2TPCConstrainedGlobal(1e10);

  trackFilter0->AddCuts(esdTrackCutsL0);

  AliAnalysisFilter* trackFilterTPC = new AliAnalysisFilter("trackFilterTPC");
  AliESDtrackCuts* esdTrackCutsTPC =
    AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
  trackFilterTPC->AddCuts(esdTrackCutsTPC);

  // Create the task and configure it
  //========================================================================
  if(typerun==2){//heavy ion analysis

    AliAnalysisTaskHighPtDeDx* taskHighPtDeDx;

    taskHighPtDeDx=0;
    Char_t TaskName[256]={0};
    sprintf(TaskName,"%s_%1.0f_%1.0f",taskname,minc,maxc);

    taskHighPtDeDx = new AliAnalysisTaskHighPtDeDx(TaskName);
    TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
    taskHighPtDeDx->SetAnalysisType(type);
    taskHighPtDeDx->SetAnalysisMC(AnalysisMC);
    taskHighPtDeDx->SetAnalysisPbPb(kTRUE);
    taskHighPtDeDx->SetProduceVZEROBranch(kTRUE);
    taskHighPtDeDx->SetProduceTPCBranch(kFALSE);
    taskHighPtDeDx->SetDebugLevel(0);
    taskHighPtDeDx->SetEtaCut(0.8);
    taskHighPtDeDx->SetVtxCut(10.0);
    taskHighPtDeDx->SetMinPt(0.0);
    taskHighPtDeDx->SetLowPtFraction(0.01); // keep 1% of tracks below min pt
    taskHighPtDeDx->SetTreeOption(1);
    taskHighPtDeDx->SetTrigger1(kTriggerInt);
    taskHighPtDeDx->SetTrigger2(kTriggerInt);
    taskHighPtDeDx->SetMinCent(minc);
    taskHighPtDeDx->SetMaxCent(maxc);
    //Set Filtesr
    taskHighPtDeDx->SetTrackFilterGolden(trackFilterGolden);
    taskHighPtDeDx->SetTrackFilter(trackFilter0);
    taskHighPtDeDx->SetTrackFilterTPC(trackFilterTPC);

    //V0's cuts
    taskHighPtDeDx->SetMassCut(0.1);
    taskHighPtDeDx->SetRequireRecV0(kTRUE); // def: kTRUE
    //taskHighPtDeDx->SetStoreMcIn(kFALSE);     // def: kFALSE
    taskHighPtDeDx->SetStoreMcIn(kTRUE);     // def: kFALSE

    mgr->AddTask(taskHighPtDeDx);

  }

  // 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
  //=======================================================================

  //before 17 aug 2015:
  //Char_t outFileName[256]={0};
  //sprintf(outFileName,"%s_Tree_%1.0f_%1.0f.root",taskname,minc,maxc);
  //cout_hist = mgr->CreateContainer(Form("output_%1.0f_%1.0f",minc,maxc), TList::Class(), AliAnalysisManager::kOutputContainer, outFileName);

  TString outFileName = Form("%s",AliAnalysisManager::GetCommonFileName());
  AliAnalysisDataContainer *cout_hist = mgr->CreateContainer(output, TList::Class(), AliAnalysisManager::kOutputContainer, outFileName);

  mgr->ConnectInput (taskHighPtDeDx, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(taskHighPtDeDx, 1, cout_hist);

  // Return task pointer at the end
  return taskHighPtDeDx;
}
if(typerun==3){//pp analysis

  AliAnalysisTaskHighPtDeDx* taskHighPtDeDx = new AliAnalysisTaskHighPtDeDx("taskHighPtDeDxpp");
  TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
  taskHighPtDeDx->SetAnalysisType(type);
  taskHighPtDeDx->SetAnalysisMC(AnalysisMC);
    taskHighPtDeDx->SetAnalysisPbPb(kFALSE);
    taskHighPtDeDx->SetProduceVZEROBranch(kTRUE);
    taskHighPtDeDx->SetProduceTPCBranch(kFALSE);
    taskHighPtDeDx->SetDebugLevel(0);
    taskHighPtDeDx->SetEtaCut(0.8);
    taskHighPtDeDx->SetVtxCut(10.0);
    taskHighPtDeDx->SetMinPt(0.0); // default 2.0
    taskHighPtDeDx->SetLowPtFraction(0.01); // keep 1% of tracks below min pt
    taskHighPtDeDx->SetTreeOption(1);
    taskHighPtDeDx->SetTrigger1(kTriggerInt);
    //    taskHighPtDeDx->SetTrigger2(kTriggerInt[1]);
    taskHighPtDeDx->SetTrigger2(kTriggerInt);
    //Set Filtesr
    taskHighPtDeDx->SetTrackFilterGolden(trackFilterGolden);
    taskHighPtDeDx->SetTrackFilter(trackFilter0);
    taskHighPtDeDx->SetTrackFilterTPC(trackFilterTPC);
    //V0's cuts
    taskHighPtDeDx->SetMassCut(0.1);         // def: 0.03
    taskHighPtDeDx->SetRequireRecV0(kTRUE); // def: kTRUE
    taskHighPtDeDx->SetStoreMcIn(kFALSE);     // def: kFALSE

    mgr->AddTask(taskHighPtDeDx);

    // 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 *cout_histdedx;

    cout_histdedx=0;
    Char_t outFileName[256]={0};
    sprintf(outFileName,"%s_Tree.root",taskname);
    //AliAnalysisDataContainer *cout_hist    = 0;

    cout_histdedx = mgr->CreateContainer("outputdedx", TList::Class(), AliAnalysisManager::kOutputContainer, outFileName);
    mgr->ConnectInput (taskHighPtDeDx, 0, mgr->GetCommonInputContainer());
    mgr->ConnectOutput(taskHighPtDeDx, 1, cout_histdedx);

    // Return task pointer at the end
    return taskHighPtDeDx;

  }

 if(typerun==4){//pPb analysis
   cout<<"<<<<<<<<<<<<<<<<<<<<<<<<<<                 Runing pPb    <<<<<<<<<<<<<<"<<endl;

    AliAnalysisTaskHighPtDeDx* taskHighPtDeDx = new AliAnalysisTaskHighPtDeDx("taskHighPtDeDxpp");
    TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
    taskHighPtDeDx->SetAnalysisType(type);
    taskHighPtDeDx->SetAnalysisMC(AnalysisMC);
    taskHighPtDeDx->SetAnalysisPbPb(kTRUE);
    taskHighPtDeDx->SetMinCent(-200);
    taskHighPtDeDx->SetMaxCent(200);
    taskHighPtDeDx->SetProduceVZEROBranch(kTRUE);
    taskHighPtDeDx->SetProduceTPCBranch(kFALSE);
    taskHighPtDeDx->SetDebugLevel(0);
    taskHighPtDeDx->SetEtaCut(0.8);
    taskHighPtDeDx->SetVtxCut(10.0);
    taskHighPtDeDx->SetMinPt(0.0); // default 2.0
    taskHighPtDeDx->SetLowPtFraction(0.01); // keep 1% of tracks below min pt
    taskHighPtDeDx->SetTreeOption(1);
    taskHighPtDeDx->SetTrigger1(kTriggerInt);
    //    taskHighPtDeDx->SetTrigger2(kTriggerInt[1]);
    taskHighPtDeDx->SetTrigger2(kTriggerInt);
    //Set Filtesr
    taskHighPtDeDx->SetTrackFilterGolden(trackFilterGolden);
    taskHighPtDeDx->SetTrackFilter(trackFilter0);
    taskHighPtDeDx->SetTrackFilterTPC(trackFilterTPC);
    //V0's cuts
    taskHighPtDeDx->SetMassCut(0.1);         // def: 0.03
    taskHighPtDeDx->SetRequireRecV0(kTRUE); // def: kTRUE
    taskHighPtDeDx->SetStoreMcIn(kTRUE);     // def: kFALSE

    mgr->AddTask(taskHighPtDeDx);

    // 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 *cout_histdedx;

    cout_histdedx=0;
    Char_t outFileName[256]={0};
    sprintf(outFileName,"%s_Tree.root",taskname);
    //AliAnalysisDataContainer *cout_hist    = 0;

    cout_histdedx = mgr->CreateContainer("outputdedx", TList::Class(), AliAnalysisManager::kOutputContainer, outFileName);
    mgr->ConnectInput (taskHighPtDeDx, 0, mgr->GetCommonInputContainer());
    mgr->ConnectOutput(taskHighPtDeDx, 1, cout_histdedx);

    // Return task pointer at the end
    return taskHighPtDeDx;

  }

}
<|endoftext|>


<commit_before>#include "MainRenderer.h"
#include "Director.h"
#include "EngineShaderFactory.hpp"
#include "ResourceManager.h"

using namespace Rendering::Camera;
using namespace Rendering::Texture;
using namespace Rendering::Shader;
using namespace Device;
using namespace Math;
using namespace Rendering::Factory;
using namespace Rendering::Light;
using namespace Rendering::Manager;
using namespace Rendering::Buffer;
using namespace Rendering::DeferredShading;
using namespace Rendering;

MainRenderer::MainRenderer() : CameraForm(),
	_blendedDepthBuffer(nullptr), _albedo_metallic(nullptr),
	_specular_fresnel0(nullptr), _normal_roughness(nullptr),
	_useTransparent(false), _opaqueDepthBuffer(nullptr),
	_tbrParamConstBuffer(nullptr), _offScreen(nullptr),
	_blendedMeshLightCulling(nullptr)
{
}

MainRenderer::~MainRenderer()
{
}

void MainRenderer::OnInitialize()
{
	CameraForm::OnInitialize();

	Size<unsigned int> backBufferSize = Director::GetInstance()->GetBackBufferSize();

	_albedo_metallic = new Texture::RenderTexture;
	ASSERT_COND_MSG( _albedo_metallic->Initialize(backBufferSize, DXGI_FORMAT_R8G8B8A8_UNORM), "GBuffer Error : cant create albedo_opacity render texture" );

	_specular_fresnel0 = new Texture::RenderTexture;
	ASSERT_COND_MSG( _specular_fresnel0->Initialize(backBufferSize, DXGI_FORMAT_R8G8B8A8_UNORM), "GBuffer Error : cant create _specular_fresnel0 render texture" );

	_normal_roughness = new Texture::RenderTexture;
	ASSERT_COND_MSG( _normal_roughness->Initialize(backBufferSize, DXGI_FORMAT_R8G8B8A8_UNORM), "GBuffer Error : cant create _normal_roughness render texture" );

	_opaqueDepthBuffer = new Texture::DepthBuffer;
	_opaqueDepthBuffer->Initialize(backBufferSize);

	EnableRenderTransparentMesh(true);

	_deferredShadingWithLightCulling = new DeferredShading::ShadingWithLightCulling;
	_deferredShadingWithLightCulling->Initialize(_opaqueDepthBuffer, _albedo_metallic, _specular_fresnel0, _normal_roughness, backBufferSize);

	_tbrParamConstBuffer = new ConstBuffer;
	_tbrParamConstBuffer->Initialize(sizeof(LightCulling::TBRParam));

	_offScreen = new OffScreen;
	_offScreen->Initialize(_deferredShadingWithLightCulling->GetOffScreen());

	auto camMgr = Device::Director::GetInstance()->GetCurrentScene()->GetCameraManager();
	CameraForm* thisCam = this;
	camMgr->Add(_owner->GetName(), thisCam);
}

void MainRenderer::OnDestroy()
{
	SAFE_DELETE(_albedo_metallic);
	SAFE_DELETE(_specular_fresnel0);
	SAFE_DELETE(_normal_roughness);
	SAFE_DELETE(_blendedDepthBuffer);

	SAFE_DELETE(_tbrParamConstBuffer);

	CameraForm::OnDestroy();
}

void MainRenderer::Render(const Device::DirectX* dx, const RenderManager* renderManager)
{
	ID3D11DeviceContext* context = dx->GetContext();

	//Clear
	{
		Color allZeroColor(0.f, 0.f, 0.f, 0.f);

		_albedo_metallic->Clear(context, allZeroColor);
		_specular_fresnel0->Clear(context, allZeroColor);
		_normal_roughness->Clear(context, allZeroColor);
	}

	_opaqueDepthBuffer->Clear(context, 0.0f, 0); //inverted depth

	if(_useTransparent)
	{
		_blendedDepthBuffer->Clear(context, 0.0f, 0);
		SortTransparentMeshRenderQueue();
	}

	// off alpha blending
	float blendFactor[4] = {0, };
	context->OMSetBlendState(dx->GetBlendStateOpaque(), blendFactor, 0xffffffff);

	struct MeshInForwardRendering
	{
		const Mesh::Mesh*	mesh;
		const Material*		material;
	};

	// TBFR = Tile Based Forward Rendering.
	// Used to render transparent meshes
	//std::vector<MeshInForwardRendering> tbfrQueue;
	//auto HasCustomShaderWithAddMeshToTBFRQueue = [&](const Material* material, const Mesh::Mesh* mesh)
	//{
	//	if( material->GetCustomShader().IsAllEmpty() == false )
	//	{
	//		MeshInForwardRendering mfr;
	//		{
	//			mfr.material = material;
	//			mfr.mesh = mesh;
	//		}
	//
	//		tbfrQueue.push_back(mfr);
	//		return true;
	//	}
	//
	//	return false;
	//};

	enum class RenderType { AlphaMesh, Opaque, Transparency, Transparency_DepthOnly };
	auto RenderMesh = [&](const std::vector<const Mesh::Mesh*>& meshes, RenderType renderType)
	{
		for(auto meshIter = meshes.begin(); meshIter != meshes.end(); ++meshIter)
		{
			const Mesh::Mesh* mesh = (*meshIter);
			Mesh::MeshFilter* filter = mesh->GetMeshFilter();
			filter->IASetBuffer(dx);

			ShaderGroup shaders;
			if(renderType == RenderType::Opaque || renderType == RenderType::AlphaMesh)
				renderManager->FindGBufferShader(shaders, filter->GetBufferFlag(), renderType == RenderType::AlphaMesh);
			else if(renderType == RenderType::Transparency || renderType == RenderType::Transparency_DepthOnly)
				renderManager->FindTransparencyShader(shaders, filter->GetBufferFlag(), renderType == RenderType::Transparency_DepthOnly);

			Mesh::MeshRenderer* renderer	= mesh->GetMeshRenderer();
			const auto& materials			= renderer->GetMaterials();
			for(auto iter = materials.begin(); iter != materials.end(); ++iter)
			{
				Material* material = (*iter);
				if(material->GetCustomShader().IsAllEmpty() == false)
				{
					DEBUG_LOG("Warning, Current version doesn't support custom shader(and normal forward rendering)");
					continue;
				}

				const auto& tex	= material->GetTextures();

				std::vector<BaseShader::BufferType> constBuffers = material->GetConstBuffers();
				{
					// Setting Camera CosntBuffer
					{
						BaseShader::BufferType buf = BaseShader::BufferType(0, _camConstBuffer, true, true, false, false);
						constBuffers.push_back(buf);
					}

					// Setting Transform ConstBuffer
					{
						BaseShader::BufferType buf = BaseShader::BufferType(1, mesh->GetTransformConstBuffer(), true, false, false, false);
						constBuffers.push_back(buf);
					}
				}

				const auto& srBuffers = material->GetShaderResourceBuffers();

				shaders.vs->SetShaderToContext(context);
				shaders.vs->SetInputLayoutToContext(context);
				shaders.vs->UpdateResources(context, &constBuffers, &tex, &srBuffers);

				if(renderType != RenderType::Transparency_DepthOnly)
				{
					shaders.ps->SetShaderToContext(context);
					shaders.ps->UpdateResources(context, &constBuffers, &tex, &srBuffers);
				}

				context->DrawIndexed(filter->GetIndexCount(), 0, 0);
			}
		}
	};

	//GBuffer
	{
		ID3D11RenderTargetView* renderTargetViews[] = {
			_albedo_metallic->GetRenderTargetView(),
			_normal_roughness->GetRenderTargetView(),
			_specular_fresnel0->GetRenderTargetView(),
		};

		context->OMSetRenderTargets(NumOfRenderTargets, renderTargetViews, _opaqueDepthBuffer->GetDepthStencilView());
		context->OMSetDepthStencilState(dx->GetDepthStateGreater(), 0);

		ID3D11SamplerState* samplerState = dx->GetSamplerStateAnisotropic();
		context->PSSetSamplers(0, 1, &samplerState);

		//Opaque Mesh
		{
			const std::vector<const Mesh::Mesh*>& meshes = renderManager->GetOpaqueMeshes().meshes.GetVector();
			RenderMesh(meshes, RenderType::Opaque);
		}

		//Alpha Test Mesh
		{
			bool useMSAA = dx->GetMSAADesc().Count > 1;

			if(useMSAA) //on alpha blending
				context->OMSetBlendState(dx->GetBlendStateAlphaToCoverage(), blendFactor, 0xffffffff);

			context->RSSetState( dx->GetRasterizerStateDisableCulling() );

			const std::vector<const Mesh::Mesh*>& meshes = renderManager->GetAlphaTestMeshes().meshes.GetVector();
			RenderMesh(meshes, RenderType::AlphaMesh);

			context->RSSetState(nullptr);

			if(useMSAA) //off alpha blending
				context->OMSetBlendState(dx->GetBlendStateOpaque(), blendFactor, 0xffffffff);
		}

		// Transparent Mesh
		// Write blended depth buffer
		if(_useTransparent)
		{
			ID3D11RenderTargetView* nullRTV = nullptr;
			context->OMSetRenderTargets(1, &nullRTV, _blendedDepthBuffer->GetDepthStencilView());

			const std::vector<const Mesh::Mesh*>& meshes = renderManager->GetTransparentMeshes().meshes.GetVector();
			RenderMesh(meshes, RenderType::Transparency_DepthOnly);
		}
	}

	LightManager* lightManager = Director::GetInstance()->GetCurrentScene()->GetLightManager();
	// Light Culling and Deferred DeferredShading
	{
		ID3D11RenderTargetView* nullRTVs[] = {nullptr, nullptr, nullptr};
		ID3D11DepthStencilView* nullDSV = nullptr;
		context->OMSetRenderTargets(NumOfRenderTargets, nullRTVs, nullDSV);
		context->OMSetDepthStencilState(dx->GetDepthStateDisableDepthTest(), 0);

		context->VSSetShader(nullptr, nullptr, 0);
		context->PSSetShader(nullptr, nullptr, 0);
		ID3D11SamplerState* nullSampler = nullptr;
		context->PSSetSamplers(0, 1, &nullSampler);

		LightCulling::TBRChangeableParam changeableParam;
		{
			changeableParam.lightNum = lightManager->GetPackedLightCount();
			GetViewMatrix(changeableParam.viewMat);

			//inverse ó, const buffer Ʈ
			GetProjectionMatrix(changeableParam.invProjMat);
		}

		if( memcmp(&_prevParamData, &changeableParam, sizeof(LightCulling::TBRChangeableParam)) != 0 )
		{
			LightCulling::TBRParam param;
			//viewMat, lightNum
			memcpy(&param, &changeableParam, sizeof(LightCulling::TBRChangeableParam));

			const Matrix& viewMat = param.viewMat;
			const Matrix& projMat = param.invProjMat; // inverse ó

			Matrix viewportMat;
			dx->GetViewportMatrix(viewportMat);

			param.invViewProjViewport = viewMat * projMat * viewportMat;
			Matrix::Inverse(param.invViewProjViewport, param.invViewProjViewport); //invViewProjViewport
			Matrix::Inverse(param.invProjMat, param.invProjMat); //invProj

			param.screenSize = Director::GetInstance()->GetBackBufferSize().Cast<float>();
			param.maxNumOfperLightInTile = LightCulling::CalcMaxNumLightsInTile();

			_tbrParamConstBuffer->UpdateSubResource(context, &param);

			_prevParamData = param;
		}

		_deferredShadingWithLightCulling->Dispatch(dx, _tbrParamConstBuffer);

		if(_useTransparent)
			_blendedMeshLightCulling->Dispatch(dx, _tbrParamConstBuffer);
	}

	// Main RT
	{
		_offScreen->Render(_renderTarget);
	}

	// Transparency
	if(_useTransparent)
	{
		ID3D11RenderTargetView* thisCamRTV = _renderTarget->GetRenderTargetView();
		context->OMSetRenderTargets(1, &thisCamRTV, _opaqueDepthBuffer->GetDepthStencilView());
		context->OMSetDepthStencilState(dx->GetDepthStateGreaterAndDisableDepthWrite(), 0x00);

		context->PSSetShaderResources(0, 1, lightManager->GetPointLightTransformBufferSR()->GetShaderResourceView());
		context->PSSetShaderResources(1, 1, lightManager->GetPointLightColorBufferSR()->GetShaderResourceView());
		context->PSSetShaderResources(2, 1, lightManager->GetSpotLightTransformBufferSR()->GetShaderResourceView());
		context->PSSetShaderResources(3, 1, lightManager->GetSpotLightColorBufferSR()->GetShaderResourceView());
		context->PSSetShaderResources(4, 1, lightManager->GetSpotLightParamBufferSR()->GetShaderResourceView());
		context->PSSetShaderResources(5, 1, lightManager->GetDirectionalLightTransformBufferSR()->GetShaderResourceView());
		context->PSSetShaderResources(6, 1, lightManager->GetDirectionalLightColorBufferSR()->GetShaderResourceView());
		context->PSSetShaderResources(7, 1, lightManager->GetDirectionalLightParamBufferSR()->GetShaderResourceView());

		const std::vector<const Mesh::Mesh*>& meshes = renderManager->GetTransparentMeshes().meshes.GetVector();
		RenderMesh(meshes, RenderType::Transparency);

		ID3D11ShaderResourceView* nullSRV = nullptr;
		context->PSSetShaderResources(0, 1, &nullSRV);
		context->PSSetShaderResources(1, 1, &nullSRV);
		context->PSSetShaderResources(2, 1, &nullSRV);
		context->PSSetShaderResources(3, 1, &nullSRV);
		context->PSSetShaderResources(4, 1, &nullSRV);
		context->PSSetShaderResources(5, 1, &nullSRV);
		context->PSSetShaderResources(6, 1, &nullSRV);
		context->PSSetShaderResources(7, 1, &nullSRV);

		context->OMSetDepthStencilState(dx->GetDepthStateGreater(), 0);
	}
}

void MainRenderer::EnableRenderTransparentMesh(bool enable)
{
	if(enable)
	{
		const Size<unsigned int> backBufferSize = Director::GetInstance()->GetBackBufferSize();

		ASSERT_COND_MSG(_blendedDepthBuffer == nullptr, "Error, Already allocated depth");
		{
			_blendedDepthBuffer =  new DepthBuffer;
			_blendedDepthBuffer->Initialize(backBufferSize);
		}

		ASSERT_COND_MSG(_blendedMeshLightCulling == nullptr, "Error, Already allocated depth");
		{
			_blendedMeshLightCulling = new OnlyLightCulling;
			_blendedMeshLightCulling->Initialize(_opaqueDepthBuffer, _blendedDepthBuffer, RenderType::TBDR);
		}
	}
	else // enable == false
	{
		SAFE_DELETE(_blendedDepthBuffer);
		SAFE_DELETE(_blendedMeshLightCulling);
	}
}

Core::Component* MainRenderer::Clone() const
{
	return nullptr;
}<commit_msg>MainRenderer - useTransparenct 버그 수정 #64<commit_after>#include "MainRenderer.h"
#include "Director.h"
#include "EngineShaderFactory.hpp"
#include "ResourceManager.h"

using namespace Rendering::Camera;
using namespace Rendering::Texture;
using namespace Rendering::Shader;
using namespace Device;
using namespace Math;
using namespace Rendering::Factory;
using namespace Rendering::Light;
using namespace Rendering::Manager;
using namespace Rendering::Buffer;
using namespace Rendering::DeferredShading;
using namespace Rendering;

MainRenderer::MainRenderer() : CameraForm(),
	_blendedDepthBuffer(nullptr), _albedo_metallic(nullptr),
	_specular_fresnel0(nullptr), _normal_roughness(nullptr),
	_useTransparent(false), _opaqueDepthBuffer(nullptr),
	_tbrParamConstBuffer(nullptr), _offScreen(nullptr),
	_blendedMeshLightCulling(nullptr)
{
}

MainRenderer::~MainRenderer()
{
}

void MainRenderer::OnInitialize()
{
	CameraForm::OnInitialize();

	Size<unsigned int> backBufferSize = Director::GetInstance()->GetBackBufferSize();

	_albedo_metallic = new Texture::RenderTexture;
	ASSERT_COND_MSG( _albedo_metallic->Initialize(backBufferSize, DXGI_FORMAT_R8G8B8A8_UNORM), "GBuffer Error : cant create albedo_opacity render texture" );

	_specular_fresnel0 = new Texture::RenderTexture;
	ASSERT_COND_MSG( _specular_fresnel0->Initialize(backBufferSize, DXGI_FORMAT_R8G8B8A8_UNORM), "GBuffer Error : cant create _specular_fresnel0 render texture" );

	_normal_roughness = new Texture::RenderTexture;
	ASSERT_COND_MSG( _normal_roughness->Initialize(backBufferSize, DXGI_FORMAT_R8G8B8A8_UNORM), "GBuffer Error : cant create _normal_roughness render texture" );

	_opaqueDepthBuffer = new Texture::DepthBuffer;
	_opaqueDepthBuffer->Initialize(backBufferSize);

	EnableRenderTransparentMesh(true);

	_deferredShadingWithLightCulling = new DeferredShading::ShadingWithLightCulling;
	_deferredShadingWithLightCulling->Initialize(_opaqueDepthBuffer, _albedo_metallic, _specular_fresnel0, _normal_roughness, backBufferSize);

	_tbrParamConstBuffer = new ConstBuffer;
	_tbrParamConstBuffer->Initialize(sizeof(LightCulling::TBRParam));

	_offScreen = new OffScreen;
	_offScreen->Initialize(_deferredShadingWithLightCulling->GetOffScreen());

	auto camMgr = Device::Director::GetInstance()->GetCurrentScene()->GetCameraManager();
	CameraForm* thisCam = this;
	camMgr->Add(_owner->GetName(), thisCam);
}

void MainRenderer::OnDestroy()
{
	SAFE_DELETE(_albedo_metallic);
	SAFE_DELETE(_specular_fresnel0);
	SAFE_DELETE(_normal_roughness);
	SAFE_DELETE(_blendedDepthBuffer);

	SAFE_DELETE(_tbrParamConstBuffer);

	CameraForm::OnDestroy();
}

void MainRenderer::Render(const Device::DirectX* dx, const RenderManager* renderManager)
{
	ID3D11DeviceContext* context = dx->GetContext();

	//Clear
	{
		Color allZeroColor(0.f, 0.f, 0.f, 0.f);

		_albedo_metallic->Clear(context, allZeroColor);
		_specular_fresnel0->Clear(context, allZeroColor);
		_normal_roughness->Clear(context, allZeroColor);
	}

	_opaqueDepthBuffer->Clear(context, 0.0f, 0); //inverted depth

	if(_useTransparent)
	{
		_blendedDepthBuffer->Clear(context, 0.0f, 0);
		SortTransparentMeshRenderQueue();
	}

	// off alpha blending
	float blendFactor[4] = {0, };
	context->OMSetBlendState(dx->GetBlendStateOpaque(), blendFactor, 0xffffffff);

	struct MeshInForwardRendering
	{
		const Mesh::Mesh*	mesh;
		const Material*		material;
	};

	// TBFR = Tile Based Forward Rendering.
	// Used to render transparent meshes
	//std::vector<MeshInForwardRendering> tbfrQueue;
	//auto HasCustomShaderWithAddMeshToTBFRQueue = [&](const Material* material, const Mesh::Mesh* mesh)
	//{
	//	if( material->GetCustomShader().IsAllEmpty() == false )
	//	{
	//		MeshInForwardRendering mfr;
	//		{
	//			mfr.material = material;
	//			mfr.mesh = mesh;
	//		}
	//
	//		tbfrQueue.push_back(mfr);
	//		return true;
	//	}
	//
	//	return false;
	//};

	enum class RenderType { AlphaMesh, Opaque, Transparency, Transparency_DepthOnly };
	auto RenderMesh = [&](const std::vector<const Mesh::Mesh*>& meshes, RenderType renderType)
	{
		for(auto meshIter = meshes.begin(); meshIter != meshes.end(); ++meshIter)
		{
			const Mesh::Mesh* mesh = (*meshIter);
			Mesh::MeshFilter* filter = mesh->GetMeshFilter();
			filter->IASetBuffer(dx);

			ShaderGroup shaders;
			if(renderType == RenderType::Opaque || renderType == RenderType::AlphaMesh)
				renderManager->FindGBufferShader(shaders, filter->GetBufferFlag(), renderType == RenderType::AlphaMesh);
			else if(renderType == RenderType::Transparency || renderType == RenderType::Transparency_DepthOnly)
				renderManager->FindTransparencyShader(shaders, filter->GetBufferFlag(), renderType == RenderType::Transparency_DepthOnly);

			Mesh::MeshRenderer* renderer	= mesh->GetMeshRenderer();
			const auto& materials			= renderer->GetMaterials();
			for(auto iter = materials.begin(); iter != materials.end(); ++iter)
			{
				Material* material = (*iter);
				if(material->GetCustomShader().IsAllEmpty() == false)
				{
					DEBUG_LOG("Warning, Current version doesn't support custom shader(and normal forward rendering)");
					continue;
				}

				const auto& tex	= material->GetTextures();

				std::vector<BaseShader::BufferType> constBuffers = material->GetConstBuffers();
				{
					// Setting Camera CosntBuffer
					{
						BaseShader::BufferType buf = BaseShader::BufferType(0, _camConstBuffer, true, true, false, false);
						constBuffers.push_back(buf);
					}

					// Setting Transform ConstBuffer
					{
						BaseShader::BufferType buf = BaseShader::BufferType(1, mesh->GetTransformConstBuffer(), true, false, false, false);
						constBuffers.push_back(buf);
					}
				}

				const auto& srBuffers = material->GetShaderResourceBuffers();

				shaders.vs->SetShaderToContext(context);
				shaders.vs->SetInputLayoutToContext(context);
				shaders.vs->UpdateResources(context, &constBuffers, &tex, &srBuffers);

				if(renderType != RenderType::Transparency_DepthOnly)
				{
					shaders.ps->SetShaderToContext(context);
					shaders.ps->UpdateResources(context, &constBuffers, &tex, &srBuffers);
				}

				context->DrawIndexed(filter->GetIndexCount(), 0, 0);
			}
		}
	};

	//GBuffer
	{
		ID3D11RenderTargetView* renderTargetViews[] = {
			_albedo_metallic->GetRenderTargetView(),
			_normal_roughness->GetRenderTargetView(),
			_specular_fresnel0->GetRenderTargetView(),
		};

		context->OMSetRenderTargets(NumOfRenderTargets, renderTargetViews, _opaqueDepthBuffer->GetDepthStencilView());
		context->OMSetDepthStencilState(dx->GetDepthStateGreater(), 0);

		ID3D11SamplerState* samplerState = dx->GetSamplerStateAnisotropic();
		context->PSSetSamplers(0, 1, &samplerState);

		//Opaque Mesh
		{
			const std::vector<const Mesh::Mesh*>& meshes = renderManager->GetOpaqueMeshes().meshes.GetVector();
			RenderMesh(meshes, RenderType::Opaque);
		}

		//Alpha Test Mesh
		{
			bool useMSAA = dx->GetMSAADesc().Count > 1;

			if(useMSAA) //on alpha blending
				context->OMSetBlendState(dx->GetBlendStateAlphaToCoverage(), blendFactor, 0xffffffff);

			context->RSSetState( dx->GetRasterizerStateDisableCulling() );

			const std::vector<const Mesh::Mesh*>& meshes = renderManager->GetAlphaTestMeshes().meshes.GetVector();
			RenderMesh(meshes, RenderType::AlphaMesh);

			context->RSSetState(nullptr);

			if(useMSAA) //off alpha blending
				context->OMSetBlendState(dx->GetBlendStateOpaque(), blendFactor, 0xffffffff);
		}

		// Transparent Mesh
		// Write blended depth buffer
		if(_useTransparent)
		{
			ID3D11RenderTargetView* nullRTV = nullptr;
			context->OMSetRenderTargets(1, &nullRTV, _blendedDepthBuffer->GetDepthStencilView());

			const std::vector<const Mesh::Mesh*>& meshes = renderManager->GetTransparentMeshes().meshes.GetVector();
			RenderMesh(meshes, RenderType::Transparency_DepthOnly);
		}
	}

	LightManager* lightManager = Director::GetInstance()->GetCurrentScene()->GetLightManager();
	// Light Culling and Deferred DeferredShading
	{
		ID3D11RenderTargetView* nullRTVs[] = {nullptr, nullptr, nullptr};
		ID3D11DepthStencilView* nullDSV = nullptr;
		context->OMSetRenderTargets(NumOfRenderTargets, nullRTVs, nullDSV);
		context->OMSetDepthStencilState(dx->GetDepthStateDisableDepthTest(), 0);

		context->VSSetShader(nullptr, nullptr, 0);
		context->PSSetShader(nullptr, nullptr, 0);
		ID3D11SamplerState* nullSampler = nullptr;
		context->PSSetSamplers(0, 1, &nullSampler);

		LightCulling::TBRChangeableParam changeableParam;
		{
			changeableParam.lightNum = lightManager->GetPackedLightCount();
			GetViewMatrix(changeableParam.viewMat);

			//inverse ó, const buffer Ʈ
			GetProjectionMatrix(changeableParam.invProjMat);
		}

		if( memcmp(&_prevParamData, &changeableParam, sizeof(LightCulling::TBRChangeableParam)) != 0 )
		{
			LightCulling::TBRParam param;
			//viewMat, lightNum
			memcpy(&param, &changeableParam, sizeof(LightCulling::TBRChangeableParam));

			const Matrix& viewMat = param.viewMat;
			const Matrix& projMat = param.invProjMat; // inverse ó

			Matrix viewportMat;
			dx->GetViewportMatrix(viewportMat);

			param.invViewProjViewport = viewMat * projMat * viewportMat;
			Matrix::Inverse(param.invViewProjViewport, param.invViewProjViewport); //invViewProjViewport
			Matrix::Inverse(param.invProjMat, param.invProjMat); //invProj

			param.screenSize = Director::GetInstance()->GetBackBufferSize().Cast<float>();
			param.maxNumOfperLightInTile = LightCulling::CalcMaxNumLightsInTile();

			_tbrParamConstBuffer->UpdateSubResource(context, &param);

			_prevParamData = param;
		}

		_deferredShadingWithLightCulling->Dispatch(dx, _tbrParamConstBuffer);

		if(_useTransparent)
			_blendedMeshLightCulling->Dispatch(dx, _tbrParamConstBuffer);
	}

	// Main RT
	{
		_offScreen->Render(_renderTarget);
	}

	// Transparency
	if(_useTransparent)
	{
		ID3D11RenderTargetView* thisCamRTV = _renderTarget->GetRenderTargetView();
		context->OMSetRenderTargets(1, &thisCamRTV, _opaqueDepthBuffer->GetDepthStencilView());
		context->OMSetDepthStencilState(dx->GetDepthStateGreaterAndDisableDepthWrite(), 0x00);

		context->PSSetShaderResources(0, 1, lightManager->GetPointLightTransformBufferSR()->GetShaderResourceView());
		context->PSSetShaderResources(1, 1, lightManager->GetPointLightColorBufferSR()->GetShaderResourceView());
		context->PSSetShaderResources(2, 1, lightManager->GetSpotLightTransformBufferSR()->GetShaderResourceView());
		context->PSSetShaderResources(3, 1, lightManager->GetSpotLightColorBufferSR()->GetShaderResourceView());
		context->PSSetShaderResources(4, 1, lightManager->GetSpotLightParamBufferSR()->GetShaderResourceView());
		context->PSSetShaderResources(5, 1, lightManager->GetDirectionalLightTransformBufferSR()->GetShaderResourceView());
		context->PSSetShaderResources(6, 1, lightManager->GetDirectionalLightColorBufferSR()->GetShaderResourceView());
		context->PSSetShaderResources(7, 1, lightManager->GetDirectionalLightParamBufferSR()->GetShaderResourceView());

		const std::vector<const Mesh::Mesh*>& meshes = renderManager->GetTransparentMeshes().meshes.GetVector();
		RenderMesh(meshes, RenderType::Transparency);

		ID3D11ShaderResourceView* nullSRV = nullptr;
		context->PSSetShaderResources(0, 1, &nullSRV);
		context->PSSetShaderResources(1, 1, &nullSRV);
		context->PSSetShaderResources(2, 1, &nullSRV);
		context->PSSetShaderResources(3, 1, &nullSRV);
		context->PSSetShaderResources(4, 1, &nullSRV);
		context->PSSetShaderResources(5, 1, &nullSRV);
		context->PSSetShaderResources(6, 1, &nullSRV);
		context->PSSetShaderResources(7, 1, &nullSRV);

		context->OMSetDepthStencilState(dx->GetDepthStateGreater(), 0);
	}
}

void MainRenderer::EnableRenderTransparentMesh(bool enable)
{
	if(enable)
	{
		const Size<unsigned int> backBufferSize = Director::GetInstance()->GetBackBufferSize();

		ASSERT_COND_MSG(_blendedDepthBuffer == nullptr, "Error, Already allocated depth");
		{
			_blendedDepthBuffer =  new DepthBuffer;
			_blendedDepthBuffer->Initialize(backBufferSize);
		}

		ASSERT_COND_MSG(_blendedMeshLightCulling == nullptr, "Error, Already allocated depth");
		{
			_blendedMeshLightCulling = new OnlyLightCulling;
			_blendedMeshLightCulling->Initialize(_opaqueDepthBuffer, _blendedDepthBuffer, RenderType::TBDR);
		}
	}
	else // enable == false
	{
		SAFE_DELETE(_blendedDepthBuffer);
		SAFE_DELETE(_blendedMeshLightCulling);
	}

	_useTransparent = enable;
}

Core::Component* MainRenderer::Clone() const
{
	return nullptr;
}<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2018.  All rights reserved
 */
#include "Stroika/Foundation/StroikaPreComp.h"

#include "Stroika/Foundation/Characters/String.h"
#include "Stroika/Foundation/Characters/StringBuilder.h"
#include "Stroika/Foundation/Characters/ToString.h"
#include "Stroika/Foundation/Containers/Mapping.h"
#include "Stroika/Foundation/DataExchange/ObjectVariantMapper.h"
#include "Stroika/Foundation/DataExchange/Variant/JSON/Reader.h"
#include "Stroika/Foundation/DataExchange/Variant/JSON/Writer.h"
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/IO/FileSystem/FileInputStream.h"
#include "Stroika/Foundation/IO/FileSystem/FileOutputStream.h"
#include "Stroika/Foundation/IO/FileSystem/WellKnownLocations.h"
#include "Stroika/Foundation/Streams/MemoryStream.h"

#include "ObjectVariantMapper.h"

using namespace std;

using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::DataExchange;

using std::byte;

namespace {
    void SimpleGettingStarted_ ()
    {
        Debug::TraceContextBumper ctx{L"SimpleGettingStarted_"};

        // Define some types that you want serialized
        struct MyType2Serialize1_ {
            bool fEnabled{false};

            // Not needed to use ObjectVariantMapper - just needed to 'test' if the data round-tripped properly
            bool operator== (const MyType2Serialize1_& rhs) const
            {
                return fEnabled == rhs.fEnabled;
            }
        };

        // Define an ObjectVariantMapper which knows how to map your types to/from VariantValue objects
        ObjectVariantMapper mapper;

        // Add the types to the mapper, which it will need
        DISABLE_COMPILER_GCC_WARNING_START ("GCC diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04
        mapper.AddClass<MyType2Serialize1_> (initializer_list<ObjectVariantMapper::StructFieldInfo>{
            {L"Enabled", Stroika_Foundation_DataExchange_StructFieldMetaInfo (MyType2Serialize1_, fEnabled)},
        });
        DISABLE_COMPILER_GCC_WARNING_END ("GCC diagnostic ignored \"-Winvalid-offsetof\"");

        // Create a test object to serialize
        MyType2Serialize1_ tmp;
        tmp.fEnabled = true;

        /// Map any arbitrary (defined in ObjectVariantMapper) object to a VariantValue
        VariantValue v = mapper.FromObject (tmp);

        // at this point - we should have VariantValue object with "Enabled" field.
        // This can then be displayed for debugging purposes using
        DbgTrace ("v = %s", Characters::ToString (v).c_str ());

        // Serialize using any serialization writer defined in Stroika::Foundation::DataExchange::Variant (we chose JSON here)
        // And dump the results into a temporary memory-based stream
        Streams::MemoryStream<byte>::Ptr tmpStream = Streams::MemoryStream<byte>::New ();
        Variant::JSON::Writer ().Write (v, tmpStream);

        // THEN deserialize, and map back to C++ object form
        MyType2Serialize1_ tmp2 = mapper.ToObject<MyType2Serialize1_> (Variant::JSON::Reader ().Read (tmpStream));

        // make sure new object matches
        Assert (tmp2 == tmp);
    }
}

namespace {
    void UseObjectVariantMapperTry2_ ()
    {
        Debug::TraceContextBumper ctx{L"UseObjectVariantMapperTry2_"};

        // Define some types that you want serialized
        struct SharedContactsConfig_ {
            bool                    fEnabled{false};
            DateTime                fLastSynchronizedAt;
            Mapping<String, String> fThisPHRsIDToSharedContactID;

            // Not needed to use ObjectVariantMapper - just needed to 'test' if the data round-tripped properly
            bool operator== (const SharedContactsConfig_& rhs) const
            {
                return fEnabled == rhs.fEnabled and
                       fLastSynchronizedAt == rhs.fLastSynchronizedAt and
                       fThisPHRsIDToSharedContactID == rhs.fThisPHRsIDToSharedContactID;
            }

            // Not needed to use ObjectVariantMapper - just to be able to print to debugger/trace-log this type
            Characters::String ToString () const
            {
                StringBuilder sb;
                sb += L"{";
                sb += L" Enabled: " + Characters::ToString (fEnabled) + L", ";
                sb += L" Last-Synchronized-At: " + Characters::ToString (fLastSynchronizedAt) + L", ";
                sb += L" This-PHRs-ID-To-Shared-Contact-ID: " + Characters::ToString (fThisPHRsIDToSharedContactID) + L", ";
                sb += L"}";
                return sb.str ();
            }
        };

        // Define an ObjectVariantMapper which knows how to map your types to/from VariantValue objects
        ObjectVariantMapper mapper;

        DISABLE_COMPILER_GCC_WARNING_START ("GCC diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04
        mapper.AddClass<SharedContactsConfig_> (initializer_list<ObjectVariantMapper::StructFieldInfo>{
            {L"Enabled", Stroika_Foundation_DataExchange_StructFieldMetaInfo (SharedContactsConfig_, fEnabled)},
            {L"Last-Synchronized-At", Stroika_Foundation_DataExchange_StructFieldMetaInfo (SharedContactsConfig_, fLastSynchronizedAt)},
            {L"This-HR-ContactID-To-SharedContactID-Map", Stroika_Foundation_DataExchange_StructFieldMetaInfo (SharedContactsConfig_, fThisPHRsIDToSharedContactID)},
        });
        DISABLE_COMPILER_GCC_WARNING_END ("GCC diagnostic ignored \"-Winvalid-offsetof\"");

        // fill in a sample object to write
        SharedContactsConfig_ tmp;
        {
            bool newEnabled = true;
            tmp.fEnabled    = newEnabled;
            tmp.fThisPHRsIDToSharedContactID.Add (L"A", L"B");
            tmp.fLastSynchronizedAt = DateTime (Time::Date (Time::Year (1998), Time::MonthOfYear::eApril, Time::DayOfMonth::e11), Time::TimeOfDay::Parse (L"3pm", locale::classic ()));
        }

        /// Map that object to a VariantValue
        VariantValue v = mapper.FromObject (tmp);

        // at this point - we should have VariantValue object with "Enabled", "Last-Synchronized-At" etc fields set properly.
        // This can then be displayed using
        DbgTrace (L"v = %s", Characters::ToString (v).c_str ());

        // Serialize using any serialization writer defined in Stroika::Foundation::DataExchange::Variant (we selected JSON)
        Streams::MemoryStream<byte>::Ptr tmpStream = Streams::MemoryStream<byte>::New ();
        Variant::JSON::Writer ().Write (v, tmpStream);

        // You can persist these to file if you wish
        constexpr bool kWrite2FileAsWell_ = true;
        if (kWrite2FileAsWell_) {
            IO::FileSystem::FileOutputStream::Ptr tmpFileStream = IO::FileSystem::FileOutputStream::New (IO::FileSystem::WellKnownLocations::GetTemporary () + L"t.txt");
            Variant::JSON::Writer ().Write (v, tmpFileStream);

            // , and then if you want, try reading it back
            IO::FileSystem::FileInputStream::Ptr tmpFileStream = IO::FileSystem::FileInputStream::New (IO::FileSystem::WellKnownLocations::GetTemporary () + L"t.txt");
            SharedContactsConfig_                tmp2          = mapper.ToObject<SharedContactsConfig_> (Variant::JSON::Reader ().Read (tmpFileStream));
            DbgTrace (L"tmp2 = %s", Characters::ToString (tmp2).c_str ());
            Assert (tmp2 == tmp);
        }

        // THEN deserialize, and map back to C++ object form
        SharedContactsConfig_ tmp2 = mapper.ToObject<SharedContactsConfig_> (Variant::JSON::Reader ().Read (tmpStream));

        // and check the roundtrip worked
        Assert (tmp2 == tmp);
    }
}

void Samples::Serialization::ObjectVariantMapper::RunDemo ()
{
    SimpleGettingStarted_ ();
    UseObjectVariantMapperTry2_ ();
}<commit_msg>cosmetic<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2018.  All rights reserved
 */
#include "Stroika/Foundation/StroikaPreComp.h"

#include "Stroika/Foundation/Characters/String.h"
#include "Stroika/Foundation/Characters/StringBuilder.h"
#include "Stroika/Foundation/Characters/ToString.h"
#include "Stroika/Foundation/Containers/Mapping.h"
#include "Stroika/Foundation/DataExchange/ObjectVariantMapper.h"
#include "Stroika/Foundation/DataExchange/Variant/JSON/Reader.h"
#include "Stroika/Foundation/DataExchange/Variant/JSON/Writer.h"
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/IO/FileSystem/FileInputStream.h"
#include "Stroika/Foundation/IO/FileSystem/FileOutputStream.h"
#include "Stroika/Foundation/IO/FileSystem/WellKnownLocations.h"
#include "Stroika/Foundation/Streams/MemoryStream.h"

#include "ObjectVariantMapper.h"

using namespace std;

using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::DataExchange;

using std::byte;

namespace {
    void SimpleGettingStarted_ ()
    {
        Debug::TraceContextBumper ctx{L"SimpleGettingStarted_"};

        // Define some types that you want serialized
        struct MyType2Serialize1_ {
            bool fEnabled{false};

            // Not needed to use ObjectVariantMapper - just needed to 'test' if the data round-tripped properly
            bool operator== (const MyType2Serialize1_& rhs) const
            {
                return fEnabled == rhs.fEnabled;
            }
        };

        // Define an ObjectVariantMapper which knows how to map your types to/from VariantValue objects
        ObjectVariantMapper mapper;

        // Add the types to the mapper, which it will need
        DISABLE_COMPILER_GCC_WARNING_START ("GCC diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04
        mapper.AddClass<MyType2Serialize1_> (initializer_list<ObjectVariantMapper::StructFieldInfo>{
            {L"Enabled", Stroika_Foundation_DataExchange_StructFieldMetaInfo (MyType2Serialize1_, fEnabled)},
        });
        DISABLE_COMPILER_GCC_WARNING_END ("GCC diagnostic ignored \"-Winvalid-offsetof\"");

        // Create a test object to serialize
        MyType2Serialize1_ tmp;
        tmp.fEnabled = true;

        /// Map any arbitrary (defined in ObjectVariantMapper) object to a VariantValue
        VariantValue v = mapper.FromObject (tmp);

        // at this point - we should have VariantValue object with "Enabled" field.
        // This can then be displayed for debugging purposes using
        DbgTrace ("v = %s", Characters::ToString (v).c_str ());

        // Serialize using any serialization writer defined in Stroika::Foundation::DataExchange::Variant (we chose JSON here)
        // And dump the results into a temporary memory-based stream
        Streams::MemoryStream<byte>::Ptr tmpStream = Streams::MemoryStream<byte>::New ();
        Variant::JSON::Writer ().Write (v, tmpStream);

        // THEN deserialize, and map back to C++ object form
        MyType2Serialize1_ tmp2 = mapper.ToObject<MyType2Serialize1_> (Variant::JSON::Reader ().Read (tmpStream));

        // make sure new object matches
        Assert (tmp2 == tmp);
    }
}

namespace {
    void UseObjectVariantMapperTry2_ ()
    {
        Debug::TraceContextBumper ctx{L"UseObjectVariantMapperTry2_"};

        // Define some types that you want serialized
        struct SharedContactsConfig_ {
            bool                    fEnabled{false};
            DateTime                fLastSynchronizedAt;
            Mapping<String, String> fThisPHRsIDToSharedContactID;

            // Not needed to use ObjectVariantMapper - just needed to 'test' if the data round-tripped properly
            bool operator== (const SharedContactsConfig_& rhs) const
            {
                return fEnabled == rhs.fEnabled and
                       fLastSynchronizedAt == rhs.fLastSynchronizedAt and
                       fThisPHRsIDToSharedContactID == rhs.fThisPHRsIDToSharedContactID;
            }

            // Not needed to use ObjectVariantMapper - just to be able to print to debugger/trace-log this type
            Characters::String ToString () const
            {
                StringBuilder sb;
                sb += L"{";
                sb += L" Enabled: " + Characters::ToString (fEnabled) + L", ";
                sb += L" Last-Synchronized-At: " + Characters::ToString (fLastSynchronizedAt) + L", ";
                sb += L" This-PHRs-ID-To-Shared-Contact-ID: " + Characters::ToString (fThisPHRsIDToSharedContactID) + L", ";
                sb += L"}";
                return sb.str ();
            }
        };

        // Define an ObjectVariantMapper which knows how to map your types to/from VariantValue objects
        ObjectVariantMapper mapper;

        DISABLE_COMPILER_GCC_WARNING_START ("GCC diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04
        mapper.AddClass<SharedContactsConfig_> (initializer_list<ObjectVariantMapper::StructFieldInfo>{
            {L"Enabled", Stroika_Foundation_DataExchange_StructFieldMetaInfo (SharedContactsConfig_, fEnabled)},
            {L"Last-Synchronized-At", Stroika_Foundation_DataExchange_StructFieldMetaInfo (SharedContactsConfig_, fLastSynchronizedAt)},
            {L"This-HR-ContactID-To-SharedContactID-Map", Stroika_Foundation_DataExchange_StructFieldMetaInfo (SharedContactsConfig_, fThisPHRsIDToSharedContactID)},
        });
        DISABLE_COMPILER_GCC_WARNING_END ("GCC diagnostic ignored \"-Winvalid-offsetof\"");

        // fill in a sample object to write
        SharedContactsConfig_ tmp;
        {
            bool newEnabled = true;
            tmp.fEnabled    = newEnabled;
            tmp.fThisPHRsIDToSharedContactID.Add (L"A", L"B");
            tmp.fLastSynchronizedAt = DateTime (Time::Date (Time::Year (1998), Time::MonthOfYear::eApril, Time::DayOfMonth::e11), Time::TimeOfDay::Parse (L"3pm", locale::classic ()));
        }

        /// Map that object to a VariantValue
        VariantValue v = mapper.FromObject (tmp);

        // at this point - we should have VariantValue object with "Enabled", "Last-Synchronized-At" etc fields set properly.
        // This can then be displayed using
        DbgTrace (L"v = %s", Characters::ToString (v).c_str ());

        // Serialize using any serialization writer defined in Stroika::Foundation::DataExchange::Variant (we selected JSON)
        Streams::MemoryStream<byte>::Ptr tmpStream = Streams::MemoryStream<byte>::New ();
        Variant::JSON::Writer ().Write (v, tmpStream);

        // You can persist these to file if you wish
        constexpr bool kWrite2FileAsWell_ = true;
        if (kWrite2FileAsWell_) {
            IO::FileSystem::FileOutputStream::Ptr tmpFileStream = IO::FileSystem::FileOutputStream::New (IO::FileSystem::WellKnownLocations::GetTemporary () + L"t.txt");
            Variant::JSON::Writer ().Write (v, tmpFileStream);

            // , and then if you want, try reading it back
            IO::FileSystem::FileInputStream::Ptr tmpFileStream = IO::FileSystem::FileInputStream::New (IO::FileSystem::WellKnownLocations::GetTemporary () + L"t.txt");
            SharedContactsConfig_                tmp2          = mapper.ToObject<SharedContactsConfig_> (Variant::JSON::Reader ().Read (tmpFileStream));
            DbgTrace (L"tmp2 = %s", Characters::ToString (tmp2).c_str ());
            Assert (tmp2 == tmp);
        }

        // THEN deserialize, and map back to C++ object form
        SharedContactsConfig_ tmp2 = mapper.ToObject<SharedContactsConfig_> (Variant::JSON::Reader ().Read (tmpStream));

        // and check the roundtrip worked
        Assert (tmp2 == tmp);
    }
}

void Samples::Serialization::ObjectVariantMapper::RunDemo ()
{
    SimpleGettingStarted_ ();
    UseObjectVariantMapperTry2_ ();
}<|endoftext|>


<commit_before>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2020 Antti Nuortimo.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

#include "child_module.hpp"
#include "parent_module.hpp"
#include "entity.hpp"

namespace yli::ontology
{
    class ParentModule;

    void ChildModule::bind_to_parent_module()
    {
        // requirements:
        // `this->parent` must not be `nullptr`.
        // `this->entity` must not be `nullptr`.

        if (this->parent_module == nullptr)
        {
            return;
        }

        if (this->entity == nullptr)
        {
            return;
        }

        // get `childID` from the `ParentModule` and set pointer to this `ChildModule`.
        this->parent_module->bind_child(this->entity);
    }

    ChildModule::~ChildModule()
    {
        // destructor.

        // requirements:
        // `this->parent` must not be `nullptr`.

        if (this->parent_module == nullptr)
        {
            return;
        }

        if (this->entity == nullptr)
        {
            return;
        }

        // Set pointer to this `Entity` to `nullptr`.
        this->parent_module->unbind_child(this->entity->childID);
    }

    yli::ontology::Entity* ChildModule::get_parent() const
    {
        if (this->parent_module == nullptr)
        {
            return nullptr;
        }

        return this->parent_module->get_entity();
    }

    void ChildModule::unbind_child() const
    {
        if (this->parent_module == nullptr)
        {
            return;
        }

        if (this->entity == nullptr)
        {
            return;
        }

        this->parent_module->unbind_child(entity->get_childID());
    }

    void ChildModule::set_parent_module_and_bind_to_new_parent(yli::ontology::ParentModule* const new_parent_module)
    {
        if (new_parent_module == nullptr)
        {
            return;
        }

        if (this->entity == nullptr)
        {
            return;
        }

        this->parent_module = new_parent_module;
        this->parent_module->bind_child(this->entity);
    }
}
<commit_msg>Edit comments.<commit_after>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2020 Antti Nuortimo.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

#include "child_module.hpp"
#include "parent_module.hpp"
#include "entity.hpp"

namespace yli::ontology
{
    class ParentModule;

    void ChildModule::bind_to_parent_module()
    {
        // requirements:
        // `this->parent` must not be `nullptr`.
        // `this->entity` must not be `nullptr`.

        if (this->parent_module == nullptr)
        {
            return;
        }

        if (this->entity == nullptr)
        {
            return;
        }

        // get `childID` from the `ParentModule` and set pointer to this child.
        this->parent_module->bind_child(this->entity);
    }

    ChildModule::~ChildModule()
    {
        // destructor.

        // requirements:
        // `this->parent` must not be `nullptr`.

        if (this->parent_module == nullptr)
        {
            return;
        }

        if (this->entity == nullptr)
        {
            return;
        }

        // Set pointer to this `Entity` to `nullptr`.
        this->parent_module->unbind_child(this->entity->childID);
    }

    yli::ontology::Entity* ChildModule::get_parent() const
    {
        if (this->parent_module == nullptr)
        {
            return nullptr;
        }

        return this->parent_module->get_entity();
    }

    void ChildModule::unbind_child() const
    {
        if (this->parent_module == nullptr)
        {
            return;
        }

        if (this->entity == nullptr)
        {
            return;
        }

        this->parent_module->unbind_child(entity->get_childID());
    }

    void ChildModule::set_parent_module_and_bind_to_new_parent(yli::ontology::ParentModule* const new_parent_module)
    {
        if (new_parent_module == nullptr)
        {
            return;
        }

        if (this->entity == nullptr)
        {
            return;
        }

        this->parent_module = new_parent_module;
        this->parent_module->bind_child(this->entity);
    }
}
<|endoftext|>