<commit_before>//_________________________________________________________________________
//  Utility Class for transverse energy studies; charged hadrons
//  Task for analysis
//  - reconstruction and MC output
// implementation file
//
//Created by Christine Nattrass, Rebecca Scott, Irakli Martashvili
//University of Tennessee at Knoxville
//_________________________________________________________________________
//Necessary to read config macros
#include <TROOT.h>
#include <TSystem.h>
#include <TInterpreter.h>

#include "TChain.h"
#include "TList.h"
#include "TH2F.h"

#include "AliESDEvent.h"
#include "AliMCEvent.h"
#include "AliESDtrackCuts.h"

#include "AliAnalysisTaskHadEt.h"
#include "AliAnalysisHadEtReconstructed.h"
#include "AliAnalysisHadEtMonteCarlo.h"

#include <iostream>

using namespace std;

ClassImp(AliAnalysisTaskHadEt)

//________________________________________________________________________
  AliAnalysisTaskHadEt::AliAnalysisTaskHadEt(const char *name, Bool_t isMc, TString recoConfigFile, TString mcConfigFile) :
        AliAnalysisTaskTransverseEnergy(name, isMc)
	,fRecAnalysis(0)
	,fMCAnalysis(0)
	,fIsSim(isMc)
{
    // Constructor
  fMCConfigFile = mcConfigFile;
  fRecoConfigFile = recoConfigFile;

  if(fMCAnalysis) delete fMCAnalysis;
  if(fRecAnalysis) delete fRecAnalysis;

  if (fRecoConfigFile.Length()) {
    cout<<"Rereading AliAnalysisHadEtReconstructed configuration file "<<fRecoConfigFile<<endl;
    gROOT->LoadMacro(fRecoConfigFile);
    fRecAnalysis = (AliAnalysisHadEtReconstructed *) gInterpreter->ProcessLine("ConfigHadEtReconstructed()");
  }

  if (fMCConfigFile.Length()) {
    cout<<"Rereading AliAnalysisHadEtMonteCarlo configuration file "<<fMCConfigFile<<endl;
    gROOT->LoadMacro(fMCConfigFile);
    fMCAnalysis = (AliAnalysisHadEtMonteCarlo *) gInterpreter->ProcessLine("ConfigHadEtMonteCarlo()");
    fMCAnalysis->SetHadEtReconstructed(fRecAnalysis);
  }

    // Define input and output slots here
    // Input slot #0 works with a TChain
    DefineInput(0, TChain::Class());
    // Output slot #1 writes into a TH1 container

    DefineOutput(1, TList::Class());
}
AliAnalysisTaskHadEt::~AliAnalysisTaskHadEt(){//Destructor
  delete fRecAnalysis;
  delete fMCAnalysis;
}

//________________________________________________________________________
void AliAnalysisTaskHadEt::UserCreateOutputObjects()
{
    // Create histograms

    // Called once

  fOutputList = new TList;
  fOutputList->SetOwner();
  fMCAnalysis->SetHistoList(fOutputList);
  fRecAnalysis->SetHistoList(fOutputList);
  if(fIsSim) fMCAnalysis->CreateHistograms();
  fRecAnalysis->CreateHistograms();

  if(fRecAnalysis->DataSet() != fMCAnalysis->DataSet()){
    cout<<"Warning: Reconstruction data set and Monte Carlo data set are not the same!  Setting data set to "<<fRecAnalysis->DataSet()<<endl;
  }

  Bool_t selectPrimaries=kTRUE;
  if(fEsdtrackCutsITSTPC) delete fEsdtrackCutsITSTPC;
  if(fEsdtrackCutsITS) delete fEsdtrackCutsITS;
  if(fEsdtrackCutsTPC) delete fEsdtrackCutsTPC;
  //We do not use these because we are using the 2010 900 GeV data
//   if(fRecAnalysis->DataSet()==2009){
//     cout<<"Setting track cuts for the 2009 p+p collisions at 900 GeV"<<endl;
//     fEsdtrackCutsITSTPC = AliESDtrackCuts::GetStandardITSTPCTrackCuts2009(selectPrimaries);
//     fEsdtrackCutsITSTPC->SetName("fEsdTrackCuts");
//     fEsdtrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
//     fEsdtrackCutsTPC->SetName("fEsdTrackCutsTPCOnly");
//     //ITS stand alone cuts - similar to 2009 cuts but with only ITS hits required
//     fEsdtrackCutsITS =  AliESDtrackCuts::GetStandardITSPureSATrackCuts2009(kTRUE,kFALSE);//we do want primaries but we do not want to require PID info
//     fEsdtrackCutsITS->SetName("fEsdTrackCutsITS");
//   }
  if(fRecAnalysis->DataSet()==2010 || fRecAnalysis->DataSet()==20111||fRecAnalysis->DataSet()==2009){
    if(fRecAnalysis->DataSet()==2010)cout<<"Setting track cuts for the 2010 p+p collisions at 7 TeV"<<endl;
    else{cout<<"Setting track cuts for the 2011 p+p collisions at 2.76 TeV"<<endl;}
    //cout<<"Warning:  Have not set 2010 track cuts yet!!"<<endl;
    fEsdtrackCutsITSTPC = AliESDtrackCuts::GetStandardITSTPCTrackCuts2010(selectPrimaries);
    fEsdtrackCutsITSTPC->SetName("fEsdTrackCuts");
    fEsdtrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
    fEsdtrackCutsTPC->SetName("fEsdTrackCutsTPCOnly");
    //ITS stand alone cuts - similar to 2009 cuts but with only ITS hits required
    fEsdtrackCutsITS =  AliESDtrackCuts::GetStandardITSPureSATrackCuts2010(kTRUE,kFALSE);//we do want primaries but we do not want to require PID info
    fEsdtrackCutsITS->SetName("fEsdTrackCutsITS");
  }
  if(fRecAnalysis->DataSet()==20100){
    cout<<"Setting track cuts for the 2010 Pb+Pb collisions at 2.76 TeV"<<endl;
    //cout<<"Warning:  Have not set 2010 track cuts yet!!"<<endl;
    fEsdtrackCutsITSTPC = AliESDtrackCuts::GetStandardITSTPCTrackCuts2010(selectPrimaries);
    fEsdtrackCutsITSTPC->SetName("fEsdTrackCuts");
    fEsdtrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
    fEsdtrackCutsTPC->SetName("fEsdTrackCutsTPCOnly");
    //ITS stand alone cuts - similar to 2009 cuts but with only ITS hits required
    fEsdtrackCutsITS =  AliESDtrackCuts::GetStandardITSSATrackCutsPbPb2010(kTRUE,kFALSE);//we do want primaries but we do not want to require PID info
    // fEsdtrackCutsITS =  AliESDtrackCuts::GetStandardITSPureSATrackCuts2010(kTRUE,kFALSE);//we do want primaries but we do not want to require PID info
   fEsdtrackCutsITS->SetName("fEsdTrackCutsITS");
  }

  fOutputList->Add(fEsdtrackCutsITSTPC);
  fOutputList->Add(fEsdtrackCutsTPC);
  fOutputList->Add(fEsdtrackCutsITS);
  if(fEsdtrackCutsITSTPC && fEsdtrackCutsTPC){
    fRecAnalysis->SetITSTrackCuts( GetITSTrackCuts());
    fMCAnalysis->SetITSTrackCuts( GetITSTrackCuts());
    fRecAnalysis->SetTPCITSTrackCuts( GetTPCITSTrackCuts());
    fMCAnalysis->SetTPCITSTrackCuts( GetTPCITSTrackCuts());
    fRecAnalysis->SetTPCOnlyTrackCuts( GetTPCOnlyTrackCuts());
    fMCAnalysis->SetTPCOnlyTrackCuts( GetTPCOnlyTrackCuts());
    //add ITS stuff!
  }
  else{
    Printf("Error: no track cuts!");
  }
}

//________________________________________________________________________
void AliAnalysisTaskHadEt::UserExec(Option_t *)
{ // execute method
  fESDEvent = dynamic_cast<AliESDEvent*>(InputEvent());
if (!fESDEvent) {
  Printf("ERROR: Could not retrieve event");
  return;
 }
//cout<<"AliAnalysisHadEtReconstructed 90"<<endl;

Int_t res = CheckPhysicsSelection(fESDEvent->GetRunNumber()); // Check if the physics selection is valid for this run

AliCentrality *cent = GetCentralityObject();

if(res == 0 && cent){

  //cout<<"New Event"<<endl;

  fRecAnalysis->AnalyseEvent(fESDEvent);

  AliMCEvent* mcEvent = MCEvent();
// if (!mcEvent) {
//   Printf("ERROR: Could not retrieve MC event");
//  }
  if (mcEvent && fESDEvent && fIsSim){
      ((AliAnalysisHadEtMonteCarlo*)fMCAnalysis)->AnalyseEvent((AliVEvent*)mcEvent,(AliVEvent*)fESDEvent);
      if(fMCAnalysis->Full()){
	fMCAnalysis->FillSimTotEtMinusRecoTotEtFullAcceptanceTPC( fRecAnalysis->GetCorrectedTotEtFullAcceptanceTPC() );
	fMCAnalysis->FillSimTotEtMinusRecoTotEtFullAcceptanceITS( fRecAnalysis->GetCorrectedTotEtFullAcceptanceITS() );
	fMCAnalysis->FillSimTotEtMinusRecoTotEtFullAcceptanceTPCNoPID( fRecAnalysis->GetCorrectedTotEtFullAcceptanceTPCNoPID() );
	fMCAnalysis->FillSimTotEtMinusRecoTotEtFullAcceptanceITSNoPID( fRecAnalysis->GetCorrectedTotEtFullAcceptanceITSNoPID() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtFullAcceptanceTPC( fRecAnalysis->GetCorrectedHadEtFullAcceptanceTPC() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtFullAcceptanceITS( fRecAnalysis->GetCorrectedHadEtFullAcceptanceITS() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtFullAcceptanceTPCNoPID( fRecAnalysis->GetCorrectedHadEtFullAcceptanceTPCNoPID() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtFullAcceptanceITSNoPID( fRecAnalysis->GetCorrectedHadEtFullAcceptanceITSNoPID() );
      }
      if(fMCAnalysis->EMCAL()){
	fMCAnalysis->FillSimTotEtMinusRecoTotEtEMCALAcceptanceTPC( fRecAnalysis->GetCorrectedTotEtEMCALAcceptanceTPC() );
	fMCAnalysis->FillSimTotEtMinusRecoTotEtEMCALAcceptanceITS( fRecAnalysis->GetCorrectedTotEtEMCALAcceptanceITS() );
	fMCAnalysis->FillSimTotEtMinusRecoTotEtEMCALAcceptanceTPCNoPID( fRecAnalysis->GetCorrectedTotEtEMCALAcceptanceTPCNoPID() );
	fMCAnalysis->FillSimTotEtMinusRecoTotEtEMCALAcceptanceITSNoPID( fRecAnalysis->GetCorrectedTotEtEMCALAcceptanceITSNoPID() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtEMCALAcceptanceTPC( fRecAnalysis->GetCorrectedHadEtEMCALAcceptanceTPC() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtEMCALAcceptanceITS( fRecAnalysis->GetCorrectedHadEtEMCALAcceptanceITS() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtEMCALAcceptanceTPCNoPID( fRecAnalysis->GetCorrectedHadEtEMCALAcceptanceTPCNoPID() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtEMCALAcceptanceITSNoPID( fRecAnalysis->GetCorrectedHadEtEMCALAcceptanceITSNoPID() );
      }
      if(fMCAnalysis->PHOS()){
	fMCAnalysis->FillSimTotEtMinusRecoTotEtPHOSAcceptanceTPC( fRecAnalysis->GetCorrectedTotEtPHOSAcceptanceTPC() );
	fMCAnalysis->FillSimTotEtMinusRecoTotEtPHOSAcceptanceITS( fRecAnalysis->GetCorrectedTotEtPHOSAcceptanceITS() );
	fMCAnalysis->FillSimTotEtMinusRecoTotEtPHOSAcceptanceTPCNoPID( fRecAnalysis->GetCorrectedTotEtPHOSAcceptanceTPCNoPID() );
	fMCAnalysis->FillSimTotEtMinusRecoTotEtPHOSAcceptanceITSNoPID( fRecAnalysis->GetCorrectedTotEtPHOSAcceptanceITSNoPID() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtPHOSAcceptanceTPC( fRecAnalysis->GetCorrectedHadEtPHOSAcceptanceTPC() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtPHOSAcceptanceITS( fRecAnalysis->GetCorrectedHadEtPHOSAcceptanceITS() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtPHOSAcceptanceTPCNoPID( fRecAnalysis->GetCorrectedHadEtPHOSAcceptanceTPCNoPID() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtPHOSAcceptanceITSNoPID( fRecAnalysis->GetCorrectedHadEtPHOSAcceptanceITSNoPID() );
      }
      if(fMCAnalysis->PiKP() && fMCAnalysis->Full()){
	fMCAnalysis->FillSimPiKPMinusRecoPiKPFullAcceptanceTPC(fRecAnalysis->GetCorrectedPiKPEtFullAcceptanceTPC());
	fMCAnalysis->FillSimPiKPMinusRecoPiKPFullAcceptanceITS(fRecAnalysis->GetCorrectedPiKPEtFullAcceptanceITS());
	fMCAnalysis->FillSimPiKPMinusRecoPiKPFullAcceptanceTPCNoPID(fRecAnalysis->GetCorrectedPiKPEtFullAcceptanceTPCNoPID());
	fMCAnalysis->FillSimPiKPMinusRecoPiKPFullAcceptanceITSNoPID(fRecAnalysis->GetCorrectedPiKPEtFullAcceptanceITSNoPID());
      }
    }
  }
//cout<<"End Event"<<endl<<endl;
// Post output data.
PostData(1, fOutputList);
}

//________________________________________________________________________
void AliAnalysisTaskHadEt::Terminate(Option_t *)
{
    // Draw result to the screen
    // Called once at the end of the query

    fOutputList = dynamic_cast<TList*> (GetOutputData(1));
    if (!fOutputList) {
        printf("ERROR: Output list not available\n");
        return;
    }
}

<commit_msg>Fixing print statements about data set configuration<commit_after>//_________________________________________________________________________
//  Utility Class for transverse energy studies; charged hadrons
//  Task for analysis
//  - reconstruction and MC output
// implementation file
//
//Created by Christine Nattrass, Rebecca Scott, Irakli Martashvili
//University of Tennessee at Knoxville
//_________________________________________________________________________
//Necessary to read config macros
#include <TROOT.h>
#include <TSystem.h>
#include <TInterpreter.h>

#include "TChain.h"
#include "TList.h"
#include "TH2F.h"

#include "AliESDEvent.h"
#include "AliMCEvent.h"
#include "AliESDtrackCuts.h"

#include "AliAnalysisTaskHadEt.h"
#include "AliAnalysisHadEtReconstructed.h"
#include "AliAnalysisHadEtMonteCarlo.h"

#include <iostream>

using namespace std;

ClassImp(AliAnalysisTaskHadEt)

//________________________________________________________________________
  AliAnalysisTaskHadEt::AliAnalysisTaskHadEt(const char *name, Bool_t isMc, TString recoConfigFile, TString mcConfigFile) :
        AliAnalysisTaskTransverseEnergy(name, isMc)
	,fRecAnalysis(0)
	,fMCAnalysis(0)
	,fIsSim(isMc)
{
    // Constructor
  fMCConfigFile = mcConfigFile;
  fRecoConfigFile = recoConfigFile;

  if(fMCAnalysis) delete fMCAnalysis;
  if(fRecAnalysis) delete fRecAnalysis;

  if (fRecoConfigFile.Length()) {
    cout<<"Rereading AliAnalysisHadEtReconstructed configuration file "<<fRecoConfigFile<<endl;
    gROOT->LoadMacro(fRecoConfigFile);
    fRecAnalysis = (AliAnalysisHadEtReconstructed *) gInterpreter->ProcessLine("ConfigHadEtReconstructed()");
  }

  if (fMCConfigFile.Length()) {
    cout<<"Rereading AliAnalysisHadEtMonteCarlo configuration file "<<fMCConfigFile<<endl;
    gROOT->LoadMacro(fMCConfigFile);
    fMCAnalysis = (AliAnalysisHadEtMonteCarlo *) gInterpreter->ProcessLine("ConfigHadEtMonteCarlo()");
    fMCAnalysis->SetHadEtReconstructed(fRecAnalysis);
  }

    // Define input and output slots here
    // Input slot #0 works with a TChain
    DefineInput(0, TChain::Class());
    // Output slot #1 writes into a TH1 container

    DefineOutput(1, TList::Class());
}
AliAnalysisTaskHadEt::~AliAnalysisTaskHadEt(){//Destructor
  delete fRecAnalysis;
  delete fMCAnalysis;
}

//________________________________________________________________________
void AliAnalysisTaskHadEt::UserCreateOutputObjects()
{
    // Create histograms

    // Called once

  fOutputList = new TList;
  fOutputList->SetOwner();
  fMCAnalysis->SetHistoList(fOutputList);
  fRecAnalysis->SetHistoList(fOutputList);
  if(fIsSim) fMCAnalysis->CreateHistograms();
  fRecAnalysis->CreateHistograms();

  if(fRecAnalysis->DataSet() != fMCAnalysis->DataSet()){
    cout<<"Warning: Reconstruction data set and Monte Carlo data set are not the same!  Setting data set to "<<fRecAnalysis->DataSet()<<endl;
  }

  Bool_t selectPrimaries=kTRUE;
  if(fEsdtrackCutsITSTPC) delete fEsdtrackCutsITSTPC;
  if(fEsdtrackCutsITS) delete fEsdtrackCutsITS;
  if(fEsdtrackCutsTPC) delete fEsdtrackCutsTPC;
  //We do not use these because we are using the 2010 900 GeV data
//   if(fRecAnalysis->DataSet()==2009){
//     cout<<"Setting track cuts for the 2009 p+p collisions at 900 GeV"<<endl;
//     fEsdtrackCutsITSTPC = AliESDtrackCuts::GetStandardITSTPCTrackCuts2009(selectPrimaries);
//     fEsdtrackCutsITSTPC->SetName("fEsdTrackCuts");
//     fEsdtrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
//     fEsdtrackCutsTPC->SetName("fEsdTrackCutsTPCOnly");
//     //ITS stand alone cuts - similar to 2009 cuts but with only ITS hits required
//     fEsdtrackCutsITS =  AliESDtrackCuts::GetStandardITSPureSATrackCuts2009(kTRUE,kFALSE);//we do want primaries but we do not want to require PID info
//     fEsdtrackCutsITS->SetName("fEsdTrackCutsITS");
//   }
  if(fRecAnalysis->DataSet()==2010 || fRecAnalysis->DataSet()==20111||fRecAnalysis->DataSet()==2009){
    if(fRecAnalysis->DataSet()==2010)cout<<"Setting track cuts for the 2010 p+p collisions at 7 TeV"<<endl;
    else{
      if(fRecAnalysis->DataSet()==2009){cout<<"Setting track cuts for the 2010 p+p collisions at 900 GeV"<<endl;}
      else{cout<<"Setting track cuts for the 2011 p+p collisions at 2.76 TeV"<<endl;}
    }
    //cout<<"Warning:  Have not set 2010 track cuts yet!!"<<endl;
    fEsdtrackCutsITSTPC = AliESDtrackCuts::GetStandardITSTPCTrackCuts2010(selectPrimaries);
    fEsdtrackCutsITSTPC->SetName("fEsdTrackCuts");
    fEsdtrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
    fEsdtrackCutsTPC->SetName("fEsdTrackCutsTPCOnly");
    //ITS stand alone cuts - similar to 2009 cuts but with only ITS hits required
    fEsdtrackCutsITS =  AliESDtrackCuts::GetStandardITSPureSATrackCuts2010(kTRUE,kFALSE);//we do want primaries but we do not want to require PID info
    fEsdtrackCutsITS->SetName("fEsdTrackCutsITS");
  }
  if(fRecAnalysis->DataSet()==20100){
    cout<<"Setting track cuts for the 2010 Pb+Pb collisions at 2.76 TeV"<<endl;
    //cout<<"Warning:  Have not set 2010 track cuts yet!!"<<endl;
    fEsdtrackCutsITSTPC = AliESDtrackCuts::GetStandardITSTPCTrackCuts2010(selectPrimaries);
    fEsdtrackCutsITSTPC->SetName("fEsdTrackCuts");
    fEsdtrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
    fEsdtrackCutsTPC->SetName("fEsdTrackCutsTPCOnly");
    //ITS stand alone cuts - similar to 2009 cuts but with only ITS hits required
    fEsdtrackCutsITS =  AliESDtrackCuts::GetStandardITSSATrackCutsPbPb2010(kTRUE,kFALSE);//we do want primaries but we do not want to require PID info
    // fEsdtrackCutsITS =  AliESDtrackCuts::GetStandardITSPureSATrackCuts2010(kTRUE,kFALSE);//we do want primaries but we do not want to require PID info
   fEsdtrackCutsITS->SetName("fEsdTrackCutsITS");
  }

  fOutputList->Add(fEsdtrackCutsITSTPC);
  fOutputList->Add(fEsdtrackCutsTPC);
  fOutputList->Add(fEsdtrackCutsITS);
  if(fEsdtrackCutsITSTPC && fEsdtrackCutsTPC){
    fRecAnalysis->SetITSTrackCuts( GetITSTrackCuts());
    fMCAnalysis->SetITSTrackCuts( GetITSTrackCuts());
    fRecAnalysis->SetTPCITSTrackCuts( GetTPCITSTrackCuts());
    fMCAnalysis->SetTPCITSTrackCuts( GetTPCITSTrackCuts());
    fRecAnalysis->SetTPCOnlyTrackCuts( GetTPCOnlyTrackCuts());
    fMCAnalysis->SetTPCOnlyTrackCuts( GetTPCOnlyTrackCuts());
    //add ITS stuff!
  }
  else{
    Printf("Error: no track cuts!");
  }
}

//________________________________________________________________________
void AliAnalysisTaskHadEt::UserExec(Option_t *)
{ // execute method
  fESDEvent = dynamic_cast<AliESDEvent*>(InputEvent());
if (!fESDEvent) {
  Printf("ERROR: Could not retrieve event");
  return;
 }
//cout<<"AliAnalysisHadEtReconstructed 90"<<endl;

Int_t res = CheckPhysicsSelection(fESDEvent->GetRunNumber()); // Check if the physics selection is valid for this run

AliCentrality *cent = GetCentralityObject();

if(res == 0 && cent){

  //cout<<"New Event"<<endl;

  fRecAnalysis->AnalyseEvent(fESDEvent);

  AliMCEvent* mcEvent = MCEvent();
// if (!mcEvent) {
//   Printf("ERROR: Could not retrieve MC event");
//  }
  if (mcEvent && fESDEvent && fIsSim){
      ((AliAnalysisHadEtMonteCarlo*)fMCAnalysis)->AnalyseEvent((AliVEvent*)mcEvent,(AliVEvent*)fESDEvent);
      if(fMCAnalysis->Full()){
	fMCAnalysis->FillSimTotEtMinusRecoTotEtFullAcceptanceTPC( fRecAnalysis->GetCorrectedTotEtFullAcceptanceTPC() );
	fMCAnalysis->FillSimTotEtMinusRecoTotEtFullAcceptanceITS( fRecAnalysis->GetCorrectedTotEtFullAcceptanceITS() );
	fMCAnalysis->FillSimTotEtMinusRecoTotEtFullAcceptanceTPCNoPID( fRecAnalysis->GetCorrectedTotEtFullAcceptanceTPCNoPID() );
	fMCAnalysis->FillSimTotEtMinusRecoTotEtFullAcceptanceITSNoPID( fRecAnalysis->GetCorrectedTotEtFullAcceptanceITSNoPID() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtFullAcceptanceTPC( fRecAnalysis->GetCorrectedHadEtFullAcceptanceTPC() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtFullAcceptanceITS( fRecAnalysis->GetCorrectedHadEtFullAcceptanceITS() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtFullAcceptanceTPCNoPID( fRecAnalysis->GetCorrectedHadEtFullAcceptanceTPCNoPID() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtFullAcceptanceITSNoPID( fRecAnalysis->GetCorrectedHadEtFullAcceptanceITSNoPID() );
      }
      if(fMCAnalysis->EMCAL()){
	fMCAnalysis->FillSimTotEtMinusRecoTotEtEMCALAcceptanceTPC( fRecAnalysis->GetCorrectedTotEtEMCALAcceptanceTPC() );
	fMCAnalysis->FillSimTotEtMinusRecoTotEtEMCALAcceptanceITS( fRecAnalysis->GetCorrectedTotEtEMCALAcceptanceITS() );
	fMCAnalysis->FillSimTotEtMinusRecoTotEtEMCALAcceptanceTPCNoPID( fRecAnalysis->GetCorrectedTotEtEMCALAcceptanceTPCNoPID() );
	fMCAnalysis->FillSimTotEtMinusRecoTotEtEMCALAcceptanceITSNoPID( fRecAnalysis->GetCorrectedTotEtEMCALAcceptanceITSNoPID() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtEMCALAcceptanceTPC( fRecAnalysis->GetCorrectedHadEtEMCALAcceptanceTPC() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtEMCALAcceptanceITS( fRecAnalysis->GetCorrectedHadEtEMCALAcceptanceITS() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtEMCALAcceptanceTPCNoPID( fRecAnalysis->GetCorrectedHadEtEMCALAcceptanceTPCNoPID() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtEMCALAcceptanceITSNoPID( fRecAnalysis->GetCorrectedHadEtEMCALAcceptanceITSNoPID() );
      }
      if(fMCAnalysis->PHOS()){
	fMCAnalysis->FillSimTotEtMinusRecoTotEtPHOSAcceptanceTPC( fRecAnalysis->GetCorrectedTotEtPHOSAcceptanceTPC() );
	fMCAnalysis->FillSimTotEtMinusRecoTotEtPHOSAcceptanceITS( fRecAnalysis->GetCorrectedTotEtPHOSAcceptanceITS() );
	fMCAnalysis->FillSimTotEtMinusRecoTotEtPHOSAcceptanceTPCNoPID( fRecAnalysis->GetCorrectedTotEtPHOSAcceptanceTPCNoPID() );
	fMCAnalysis->FillSimTotEtMinusRecoTotEtPHOSAcceptanceITSNoPID( fRecAnalysis->GetCorrectedTotEtPHOSAcceptanceITSNoPID() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtPHOSAcceptanceTPC( fRecAnalysis->GetCorrectedHadEtPHOSAcceptanceTPC() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtPHOSAcceptanceITS( fRecAnalysis->GetCorrectedHadEtPHOSAcceptanceITS() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtPHOSAcceptanceTPCNoPID( fRecAnalysis->GetCorrectedHadEtPHOSAcceptanceTPCNoPID() );
	fMCAnalysis->FillSimHadEtMinusRecoHadEtPHOSAcceptanceITSNoPID( fRecAnalysis->GetCorrectedHadEtPHOSAcceptanceITSNoPID() );
      }
      if(fMCAnalysis->PiKP() && fMCAnalysis->Full()){
	fMCAnalysis->FillSimPiKPMinusRecoPiKPFullAcceptanceTPC(fRecAnalysis->GetCorrectedPiKPEtFullAcceptanceTPC());
	fMCAnalysis->FillSimPiKPMinusRecoPiKPFullAcceptanceITS(fRecAnalysis->GetCorrectedPiKPEtFullAcceptanceITS());
	fMCAnalysis->FillSimPiKPMinusRecoPiKPFullAcceptanceTPCNoPID(fRecAnalysis->GetCorrectedPiKPEtFullAcceptanceTPCNoPID());
	fMCAnalysis->FillSimPiKPMinusRecoPiKPFullAcceptanceITSNoPID(fRecAnalysis->GetCorrectedPiKPEtFullAcceptanceITSNoPID());
      }
    }
  }
//cout<<"End Event"<<endl<<endl;
// Post output data.
PostData(1, fOutputList);
}

//________________________________________________________________________
void AliAnalysisTaskHadEt::Terminate(Option_t *)
{
    // Draw result to the screen
    // Called once at the end of the query

    fOutputList = dynamic_cast<TList*> (GetOutputData(1));
    if (!fOutputList) {
        printf("ERROR: Output list not available\n");
        return;
    }
}

<|endoftext|>


<commit_before>#ifndef _drc_RansacGeneric_hpp_
#define _drc_RansacGeneric_hpp_

#include <cmath>
#include <vector>
#include <algorithm>

namespace drc {

template<typename Problem>
class RansacGeneric {
public:
  struct Result {
    bool mSuccess;
    typename Problem::Solution mSolution;
    std::vector<int> mInliers;
    int mNumIterations;
  };

public:
  RansacGeneric() {
    setMaximumIterations(5000);
    setGoodSolutionProbability(1-1e-8);
    setRefineUsingInliers(false);
    setMaximumError(-1);
  }

  virtual ~RansacGeneric() {}

  void setMaximumIterations(const int iIters) { mMaximumIterations = iIters; }
  void setGoodSolutionProbability(const double iProb) {
    mGoodSolutionProbability = iProb;
  }
  void setRefineUsingInliers(const bool iVal) { mRefineUsingInliers = iVal; }
  void setMaximumError(const double iVal) { mMaximumError = iVal; }

  Result solve(const Problem& iProblem) const {
    // set up initial (empty) result
    Result result;
    result.mSuccess = false;
    result.mNumIterations = 0;

    // ensure that there are enough data points to proceed
    const int sampleSize = iProblem.getSampleSize();
    const int n = iProblem.getNumDataPoints();
    if (n < sampleSize) {
      return result;
    }

    const double epsilon = 1e-10;

    // best results are currently invalid
    double bestScore = -1;
    bool success = false;

    // start number of iterations as infinite, then reduce as we go
    double numIterationsNeeded = 1e10;
    int iterationCount = 0;
    int skippedSampleCount = 0;

    // for random sample index generation
    std::vector<int> allIndices(n);

    // iterate until adaptive number of iterations are exceeded
    while (iterationCount < numIterationsNeeded) {

      // determine random sample indices
      for (int i = 0; i < n; ++i) {
        allIndices[i] = i;
      }
      for (int i = 0; i < sampleSize; ++i) {
        int randIndex = std::rand() % n;
        std::swap(allIndices[i], allIndices[randIndex]);
      }
      std::vector<int> sampleIndices(allIndices.begin(),
                                     allIndices.begin() + sampleSize);

      // compute solution on minimal set
      typename Problem::Solution solution = iProblem.estimate(sampleIndices);

      // compute errors over all data points
      std::vector<double> errors2 = iProblem.computeSquaredErrors(solution);

      // check whether this is a valid sample
      // TODO: this should be done via a method in Problem class, but would
      // require changing all existing usages to include that method
      if (errors2.size() == 0) {
        ++skippedSampleCount;
        if (skippedSampleCount >= mMaximumIterations) break;
        continue;
      }
      skippedSampleCount = 0;

      // compute error threshold to be applied to each term
      double thresh = mMaximumError;
      if (thresh < 0) {
        std::sort(errors2.begin(), errors2.end());
        double median = (n % 2 == 0) ?
          (0.5*(errors2[n/2]+errors2[n/2+1])) : errors2[n/2];
        thresh = 1.4826*std::sqrt(median)*4.6851;
      }
      thresh *= thresh;

      // determine inliers
      std::vector<int> inliers;
      inliers.reserve(n);
      for (int i = 0; i < n; ++i) {
        if (errors2[i] <= thresh) {
          inliers.push_back(i);
        }
      }

      // if this is the best score, update solution and convergence criteria
      double score = inliers.size();
      if (score > bestScore) {
        bestScore = score;
        result.mInliers = inliers;
        result.mSolution = solution;
        success = true;
        double inlierProbability = double(inliers.size()) / n;
        double anyOutlierProbability = 1 - pow(inlierProbability,sampleSize);
        anyOutlierProbability = std::min(anyOutlierProbability, 1-epsilon);
        anyOutlierProbability = std::max(anyOutlierProbability, epsilon);
        numIterationsNeeded =
          log(1-mGoodSolutionProbability) / log(anyOutlierProbability);
      }

      // bump up iteration count and terminate if it exceeds hard max
      ++iterationCount;
      if (iterationCount > mMaximumIterations) {
        break;
      }
    }

    // finish off result params
    result.mSuccess = success;
    result.mNumIterations = iterationCount;

    // refine result using all inliers if specified
    if (result.mSuccess && mRefineUsingInliers) {
      result.mSolution = iProblem.estimate(result.mInliers);
    }

    // done
    return result;
  }

protected:
  bool mRefineUsingInliers;
  int mMaximumIterations;
  double mGoodSolutionProbability;
  double mMaximumError;
};

}

#endif
<commit_msg>prevent success flag when num inliers = 0<commit_after>#ifndef _drc_RansacGeneric_hpp_
#define _drc_RansacGeneric_hpp_

#include <cmath>
#include <vector>
#include <algorithm>

namespace drc {

template<typename Problem>
class RansacGeneric {
public:
  struct Result {
    bool mSuccess;
    typename Problem::Solution mSolution;
    std::vector<int> mInliers;
    int mNumIterations;
  };

public:
  RansacGeneric() {
    setMaximumIterations(5000);
    setGoodSolutionProbability(1-1e-8);
    setRefineUsingInliers(false);
    setMaximumError(-1);
  }

  virtual ~RansacGeneric() {}

  void setMaximumIterations(const int iIters) { mMaximumIterations = iIters; }
  void setGoodSolutionProbability(const double iProb) {
    mGoodSolutionProbability = iProb;
  }
  void setRefineUsingInliers(const bool iVal) { mRefineUsingInliers = iVal; }
  void setMaximumError(const double iVal) { mMaximumError = iVal; }

  Result solve(const Problem& iProblem) const {
    // set up initial (empty) result
    Result result;
    result.mSuccess = false;
    result.mNumIterations = 0;

    // ensure that there are enough data points to proceed
    const int sampleSize = iProblem.getSampleSize();
    const int n = iProblem.getNumDataPoints();
    if (n < sampleSize) {
      return result;
    }

    const double epsilon = 1e-10;

    // best results are currently invalid
    int bestScore = 0;
    bool success = false;

    // start number of iterations as infinite, then reduce as we go
    double numIterationsNeeded = 1e10;
    int iterationCount = 0;
    int skippedSampleCount = 0;

    // for random sample index generation
    std::vector<int> allIndices(n);

    // iterate until adaptive number of iterations are exceeded
    while (iterationCount < numIterationsNeeded) {

      // determine random sample indices
      for (int i = 0; i < n; ++i) {
        allIndices[i] = i;
      }
      for (int i = 0; i < sampleSize; ++i) {
        int randIndex = std::rand() % n;
        std::swap(allIndices[i], allIndices[randIndex]);
      }
      std::vector<int> sampleIndices(allIndices.begin(),
                                     allIndices.begin() + sampleSize);

      // compute solution on minimal set
      typename Problem::Solution solution = iProblem.estimate(sampleIndices);

      // compute errors over all data points
      std::vector<double> errors2 = iProblem.computeSquaredErrors(solution);

      // check whether this is a valid sample
      // TODO: this should be done via a method in Problem class, but would
      // require changing all existing usages to include that method
      if (errors2.size() == 0) {
        ++skippedSampleCount;
        if (skippedSampleCount >= mMaximumIterations) break;
        continue;
      }
      skippedSampleCount = 0;

      // compute error threshold to be applied to each term
      double thresh = mMaximumError;
      if (thresh < 0) {
        std::sort(errors2.begin(), errors2.end());
        double median = (n % 2 == 0) ?
          (0.5*(errors2[n/2]+errors2[n/2+1])) : errors2[n/2];
        thresh = 1.4826*std::sqrt(median)*4.6851;
      }
      thresh *= thresh;

      // determine inliers
      std::vector<int> inliers;
      inliers.reserve(n);
      for (int i = 0; i < n; ++i) {
        if (errors2[i] <= thresh) {
          inliers.push_back(i);
        }
      }

      // if this is the best score, update solution and convergence criteria
      int score = inliers.size();
      if (score > bestScore) {
        bestScore = score;
        result.mInliers = inliers;
        result.mSolution = solution;
        success = true;
        double inlierProbability = double(inliers.size()) / n;
        double anyOutlierProbability = 1 - pow(inlierProbability,sampleSize);
        anyOutlierProbability = std::min(anyOutlierProbability, 1-epsilon);
        anyOutlierProbability = std::max(anyOutlierProbability, epsilon);
        numIterationsNeeded =
          log(1-mGoodSolutionProbability) / log(anyOutlierProbability);
      }

      // bump up iteration count and terminate if it exceeds hard max
      ++iterationCount;
      if (iterationCount > mMaximumIterations) {
        break;
      }
    }

    // finish off result params
    result.mSuccess = success;
    result.mNumIterations = iterationCount;

    // refine result using all inliers if specified
    if (result.mSuccess && mRefineUsingInliers) {
      result.mSolution = iProblem.estimate(result.mInliers);
    }

    // done
    return result;
  }

protected:
  bool mRefineUsingInliers;
  int mMaximumIterations;
  double mGoodSolutionProbability;
  double mMaximumError;
};

}

#endif
<|endoftext|>


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

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medickal and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/ for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "SampleApp.h"

#include <QmitkStdMultiWidget.h>
#include <QmitkSelectableGLWidget.h>
#include <QmitkCommonFunctionality.h>

#include <mitkStatusBar.h>

#include <QmitkFunctionality.h>
#include <QmitkFunctionalityFactory.h>
#include <QmitkFctMediator.h>
#include <QmitkControlsRightFctLayoutTemplate.h>
#include <QmitkControlsLeftFctLayoutTemplate.h>

#include <qlayout.h>

void RegisterFunctionalities();

SampleApp::SampleApp( QWidget* parent, const char* name, WFlags fl, const char* testingParameter ):
QmitkMainTemplate( parent, name, fl ), m_ControlsLeft ( false ), m_TestingParameter(testingParameter)
{
  RegisterFunctionalities();
  this->setCaption("MITK Application");
  std::cout << "Instantiating new SampleApp..." << std::endl;

  QmitkMainTemplate::Initialize();

  parseCommandLine();

  resize(1024,768);

}
/*
*  Destroys the object and frees any allocated resources
*/
SampleApp::~SampleApp()
{
  // no need to delete child widgets, Qt does it all for us
}

void SampleApp::InitializeFunctionality()
{
  m_MultiWidget->mitkWidget4->GetRenderer()->SetMapperID(2);
  //create and add functionalities. Functionalities are also invisible objects, which can be asked to
  //create their different parts (main widget, control widget, toolbutton for selection).
  mitk::DataTreePreOrderIterator iterator(m_Tree);

  QmitkFunctionalityFactory& qff = QmitkFunctionalityFactory::GetInstance();
  if (!m_TestingParameter) {
    // add all known functionalities
    for (QmitkFunctionalityFactory::CreateFunctionalityPtrMap::const_iterator it = qff.GetCreateFunctionalityPtrMap().begin() ; it != qff.GetCreateFunctionalityPtrMap().end(); it++)
    {
    QmitkFunctionality* functionalityInstance = ((*it).second)(qfm,m_MultiWidget,&iterator);
      qfm->AddFunctionality(functionalityInstance);
    }
  }
  else {
    //
    QmitkFunctionalityFactory::CreateFunctionalityPtr createFunction = qff.GetCreateFunctionalityPtrByName(m_TestingParameter);
   if (createFunction) {
     createFunction(qfm,m_MultiWidget,&iterator);
   }
  }

  mitk::StatusBar::GetInstance()->DisplayText("Functionalities added",3000);
}

void SampleApp::InitializeQfm()
{
  if (m_ControlsLeft) {
    //create an QmitkFctMediator. This is an invisible object that controls, manages and mediates functionalities
    qfm=new QmitkFctMediator(this);

    //create an QmitkButtonFctLayoutTemplate. This is an simple example for an layout of the different widgets, of which
    //a functionality and the management consists: the main widget, the control widget and a menu for selecting the
    //active functionality.
    QmitkControlsLeftFctLayoutTemplate* layoutTemplate=new QmitkControlsLeftFctLayoutTemplate(this, "LayoutTemplate");
    setCentralWidget(layoutTemplate);

    //let the QmitkFctMediator know about the layout. This includes the toolbar and the layoutTemplate.
    qfm->Initialize(this);
  }
  else
  {
    QmitkMainTemplate::InitializeQfm();
  }
}

<commit_msg>COMP: trigger dashboard rebuild and FIX for bug #500 <commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medickal and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/ for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "SampleApp.h"

#include <QmitkStdMultiWidget.h>
#include <QmitkSelectableGLWidget.h>
#include <QmitkCommonFunctionality.h>

#include <mitkStatusBar.h>

#include <QmitkFunctionality.h>
#include <QmitkFunctionalityFactory.h>
#include <QmitkFctMediator.h>
#include <QmitkControlsRightFctLayoutTemplate.h>
#include <QmitkControlsLeftFctLayoutTemplate.h>

#include <qlayout.h>

void RegisterFunctionalities();

SampleApp::SampleApp( QWidget* parent, const char* name, WFlags fl, const char* testingParameter ):
QmitkMainTemplate( parent, name, fl ), m_ControlsLeft ( false ), m_TestingParameter(testingParameter)
{
  RegisterFunctionalities();
  this->setCaption("MITK Application");
  std::cout << "Instantiating new SampleApp..." << std::endl;

  QmitkMainTemplate::Initialize();

  parseCommandLine();

  resize(1024,768);

}
/*
*  Destroys the object and frees any allocated resources
*/
SampleApp::~SampleApp()
{
  // no need to delete child widgets, Qt does it all for us
}

void SampleApp::InitializeFunctionality()
{
  m_MultiWidget->mitkWidget4->GetRenderer()->SetMapperID(2);
  //create and add functionalities. Functionalities are also invisible objects, which can be asked to
  //create their different parts (main widget, control widget, toolbutton for selection).
  mitk::DataTreePreOrderIterator iterator(m_Tree);

  QmitkFunctionalityFactory& qff = QmitkFunctionalityFactory::GetInstance();
  if (!m_TestingParameter) {
    QmitkFunctionalityFactory::CreateFunctionalityPtr createFunction = qff.GetCreateFunctionalityPtrByName("QmitkSimpleExampleFunctionality");
   if (createFunction) {
     QmitkFunctionality* functionalityInstance = createFunction(qfm,m_MultiWidget,&iterator);
     qfm->AddFunctionality(functionalityInstance);
   }

    // add all known functionalities
    for (QmitkFunctionalityFactory::CreateFunctionalityPtrMap::const_iterator it = qff.GetCreateFunctionalityPtrMap().begin() ; it != qff.GetCreateFunctionalityPtrMap().end(); it++)
    {
      if ( qfm->GetFunctionalityByName( (*it).first.c_str() ) == NULL ) {
        QmitkFunctionality* functionalityInstance = ((*it).second)(qfm,m_MultiWidget,&iterator);
        qfm->AddFunctionality(functionalityInstance);
      }
    }
  }
  else {
    //
    QmitkFunctionalityFactory::CreateFunctionalityPtr createFunction = qff.GetCreateFunctionalityPtrByName(m_TestingParameter);
   if (createFunction) {
     QmitkFunctionality* functionalityInstance = createFunction(qfm,m_MultiWidget,&iterator);
     qfm->AddFunctionality(functionalityInstance);
   }
  }

  mitk::StatusBar::GetInstance()->DisplayText("Functionalities added",3000);
}

void SampleApp::InitializeQfm()
{
  if (m_ControlsLeft) {
    //create an QmitkFctMediator. This is an invisible object that controls, manages and mediates functionalities
    qfm=new QmitkFctMediator(this);

    //create an QmitkButtonFctLayoutTemplate. This is an simple example for an layout of the different widgets, of which
    //a functionality and the management consists: the main widget, the control widget and a menu for selecting the
    //active functionality.
    QmitkControlsLeftFctLayoutTemplate* layoutTemplate=new QmitkControlsLeftFctLayoutTemplate(this, "LayoutTemplate");
    setCentralWidget(layoutTemplate);

    //let the QmitkFctMediator know about the layout. This includes the toolbar and the layoutTemplate.
    qfm->Initialize(this);
  }
  else
  {
    QmitkMainTemplate::InitializeQfm();
  }
}

<|endoftext|>


<commit_before>#include "CameraBase.h"
#include "sys/SysControl.h"
#include "HMDWrapper.h"
#include "Engine.h"
#include "Game.h"

using namespace MathLib;

#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO

#define CAMERA_BASE_CLAMP            89.9f

CCameraBase::CCameraBase(): CPlayer(PLAYER_SPECTATOR)
{
	m_nFlush = 0;
    m_vPosition = Vec3_zero;
    m_fPhiAngle = 0.0f;
    m_fThetaAngle = 0.0f;
    m_pLastPlayer = NULL;
	m_nEnabelMouse = 1;
    SetRadius(1.0f);

	SetMinThetaAngle(-90.0f);
    SetMaxThetaAngle(90.0f);
    SetTurning(90.0f);

    SetViewDirection(vec3(0.0f,1.0f,0.0f));

    SetEnabled(0);
    SetHMDEnabled(1);
}

CCameraBase::~CCameraBase()
{
    Leave();
}

void CCameraBase::SetEnabled(int nEnable)
{
	if(nEnable)
	{
		m_pLastPlayer =  g_Engine.pGame->GetPlayer();
        CPlayer::SetEnabled(nEnable);
		g_Engine.pGame->SetPlayer(this);

	}
	else
	{
		if (m_pLastPlayer)
        {
            g_Engine.pGame->SetPlayer(m_pLastPlayer);
            CPlayer::SetEnabled(nEnable);
        }
	}
}

int CCameraBase::IsEnabled() const
{
    return CPlayer::IsEnabled();
}
void CCameraBase::SetHMDEnabled(int nEnable)
{
    m_nHMDEnable = nEnable;
}

int CCameraBase::IsHMDEnabled() const
{
    return m_nHMDEnable;
}

void CCameraBase::SetRadius(float r)
{
    m_fRadius = r;
}

float CCameraBase::GetRadius() const
{
    return m_fRadius;
}
/******************************************************************************\
*
* Parameters
*
\******************************************************************************/

/*
 */
void CCameraBase::Update_Bounds()
{
    m_BoundSphere.Set(vec3_zero,m_fRadius);
    m_BoundBox.Set(m_BoundSphere);
    Update_World_Position();
}

void CCameraBase::SetMinThetaAngle(float angle)
{
    m_fMinThetaAngle = Clamp(angle,-CAMERA_BASE_CLAMP,CAMERA_BASE_CLAMP);
}

float CCameraBase::GetMinThetaAngle() const
{
    return m_fMinThetaAngle;
}

/*
*/
void CCameraBase::SetMaxThetaAngle(float angle)
{
	m_fMaxThetaAngle = Clamp(angle, -CAMERA_BASE_CLAMP, CAMERA_BASE_CLAMP);
}
float CCameraBase::GetMaxThetaAngle() const
{
	return m_fMaxThetaAngle;
}
float CCameraBase::GetTurning() const
{
	return m_fTurning;
}
void CCameraBase::SetPhiAngle(float angle)
{
	FlushTransform();
}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "CameraBase.h"
#include "sys/SysControl.h"
#include "HMDWrapper.h"
#include "Engine.h"
#include "Game.h"

using namespace MathLib;

#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO

#define CAMERA_BASE_CLAMP            89.9f

CCameraBase::CCameraBase(): CPlayer(PLAYER_SPECTATOR)
{
	m_nFlush = 0;
    m_vPosition = Vec3_zero;
    m_fPhiAngle = 0.0f;
    m_fThetaAngle = 0.0f;
    m_pLastPlayer = NULL;
	m_nEnabelMouse = 1;
    SetRadius(1.0f);

	SetMinThetaAngle(-90.0f);
    SetMaxThetaAngle(90.0f);
    SetTurning(90.0f);

    SetViewDirection(vec3(0.0f,1.0f,0.0f));

    SetEnabled(0);
    SetHMDEnabled(1);
}

CCameraBase::~CCameraBase()
{
    Leave();
}

void CCameraBase::SetEnabled(int nEnable)
{
	if(nEnable)
	{
		m_pLastPlayer =  g_Engine.pGame->GetPlayer();
        CPlayer::SetEnabled(nEnable);
		g_Engine.pGame->SetPlayer(this);

	}
	else
	{
		if (m_pLastPlayer)
        {
            g_Engine.pGame->SetPlayer(m_pLastPlayer);
            CPlayer::SetEnabled(nEnable);
        }
	}
}

int CCameraBase::IsEnabled() const
{
    return CPlayer::IsEnabled();
}
void CCameraBase::SetHMDEnabled(int nEnable)
{
    m_nHMDEnable = nEnable;
}

int CCameraBase::IsHMDEnabled() const
{
    return m_nHMDEnable;
}

void CCameraBase::SetRadius(float r)
{
    m_fRadius = r;
}

float CCameraBase::GetRadius() const
{
    return m_fRadius;
}
/******************************************************************************\
*
* Parameters
*
\******************************************************************************/

/*
 */
void CCameraBase::Update_Bounds()
{
    m_BoundSphere.Set(vec3_zero,m_fRadius);
    m_BoundBox.Set(m_BoundSphere);
    Update_World_Position();
}

void CCameraBase::SetMinThetaAngle(float angle)
{
    m_fMinThetaAngle = Clamp(angle,-CAMERA_BASE_CLAMP,CAMERA_BASE_CLAMP);
}

float CCameraBase::GetMinThetaAngle() const
{
    return m_fMinThetaAngle;
}

/*
*/
void CCameraBase::SetMaxThetaAngle(float angle)
{
	m_fMaxThetaAngle = Clamp(angle, -CAMERA_BASE_CLAMP, CAMERA_BASE_CLAMP);
}
float CCameraBase::GetMaxThetaAngle() const
{
	return m_fMaxThetaAngle;
}
float CCameraBase::GetTurning() const
{
	return m_fTurning;
}
void CCameraBase::SetPhiAngle(float angle)
{
	angle = angle - m_fPhiAngle;

	FlushTransform();
}<|endoftext|>


<commit_before>#include "Common.h"
#include <SDL.h>
#include <SDL_image.h>
#include <iostream>
#include <Graphics/OpenGL.h>
#include <Graphics/Shader.h>
#include <Graphics/Texture.h>
#include <Graphics/Mesh.h>
#include <Graphics/Material.h>
using namespace Graphics;
#include <Utils/Input.h>
using namespace Utils;

void Init();
void Update();
void Display();

Input input;
Mesh mesh;
Shader shader;
Texture texture;
Material material;

Vector3 cameraPos = Vector3(0, 2, 0);
Vector2 cameraRot;

int main(int argc, char **argv)
{
    bool running = true;

    if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
    {
        std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
        return 1;
    }

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 4);

    SDL_Window* window = SDL_CreateWindow("Title",
        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
        800, 600, SDL_WINDOW_OPENGL);

    SDL_GLContext context = SDL_GL_CreateContext(window);

    glewExperimental = true;
    glewInit();

    //GLEW causes an error for some reason
    auto error = glGetError();

    std::cout << "OpenGL Renderer: " << (char*)glGetString(GL_RENDERER) << std::endl;
    std::cout << "OpenGL Version: " << (char*)glGetString(GL_VERSION) << std::endl;

    IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG);

    Init();

    while (running)
    {
        SDL_Event event;
        while (SDL_PollEvent(&event))
        {
            if (event.type == SDL_EventType::SDL_QUIT)
            {
                running = false;
            }
        }

        Update();
        Display();

        SDL_GL_SwapWindow(window);
    }

    IMG_Quit();

    SDL_GL_DeleteContext(context);
    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;
}

void Init()
{
    shader.LoadFromFiles("Data/Diffuse.vert", "Data/Diffuse.frag");
    shader.Start();

    mesh.LoadObjFile("Data/Hallway.obj");

    texture.Load("Data/Hallway.png");

    material.SetShader(shader);
    material.SetTexture(shader.GetUniformLocation("tex_diffuse"), texture);

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);

    glClearColor(0.1f, 0.1f, 0.1f, 0.0f);

    SDL_SetRelativeMouseMode(SDL_TRUE);
}

void Update()
{
    input.Update();

    const float sensitivity = 0.2f;
    cameraRot.x -= sensitivity * input.GetRelativeMouseX();
    cameraRot.y = Math::Clamp(cameraRot.y - sensitivity * input.GetRelativeMouseY(), -90.0f, 90.0f);

    //Forward and back
    if (input.KeyDown(SDL_SCANCODE_W))
    {
        cameraPos -= 0.1f * Vector3(Math::SinDeg(cameraRot.x), 0, Math::CosDeg(cameraRot.x));
    }
    else if (input.KeyDown(SDL_SCANCODE_S))
    {
        cameraPos += 0.1f * Vector3(Math::SinDeg(cameraRot.x), 0, Math::CosDeg(cameraRot.x));
    }

    //Left and right
    if (input.KeyDown(SDL_SCANCODE_A))
    {
        cameraPos -= 0.1f * Vector3(Math::CosDeg(cameraRot.x), 0, -Math::SinDeg(cameraRot.x));
    }
    else if (input.KeyDown(SDL_SCANCODE_D))
    {
        cameraPos += 0.1f * Vector3(Math::CosDeg(cameraRot.x), 0, -Math::SinDeg(cameraRot.x));
    }

    //Up and down
    if (input.KeyDown(SDL_SCANCODE_Q))
    {
        cameraPos.y -= 0.1f;
    }
    else if (input.KeyDown(SDL_SCANCODE_E))
    {
        cameraPos.y += 0.1f;
    }
}

void Display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    auto projection = Matrix4x4::Perspective(60, 4.0f / 3.0f, 0.01f, 1000);
    auto view = Matrix4x4::FromTransform(
        cameraPos,
        Quaternion::AngleAxis(cameraRot.x, Vector3::up) * Quaternion::AngleAxis(cameraRot.y, Vector3::right),
        Vector3::one).GetInverse();
    auto matrix = projection * view * Matrix4x4::FromPosition(Vector3(0, 0, -4));
    glUniformMatrix4fv(shader.GetUniformLocation("in_modelview"), 1, false, &matrix[0]);

    material.Start();
    mesh.Draw();

    auto error = glGetError();
    if (error != GL_NO_ERROR)
    {
        std::cout << error << " : " << glewGetErrorString(error);
    }
}
<commit_msg>Used quaternion/vector multiplication to calculate camera movement directions.<commit_after>#include "Common.h"
#include <SDL.h>
#include <SDL_image.h>
#include <iostream>
#include <Graphics/OpenGL.h>
#include <Graphics/Shader.h>
#include <Graphics/Texture.h>
#include <Graphics/Mesh.h>
#include <Graphics/Material.h>
using namespace Graphics;
#include <Utils/Input.h>
using namespace Utils;

void Init();
void Update();
void Display();

Input input;
Mesh mesh;
Shader shader;
Texture texture;
Material material;

Vector3 cameraPos = Vector3(0, 2, 0);
Vector2 cameraRot;

int main(int argc, char **argv)
{
    bool running = true;

    if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
    {
        std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
        return 1;
    }

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 4);

    SDL_Window* window = SDL_CreateWindow("Title",
        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
        1280, 720, SDL_WINDOW_OPENGL);

    SDL_GLContext context = SDL_GL_CreateContext(window);

    glewExperimental = true;
    glewInit();

    //GLEW causes an error for some reason
    auto error = glGetError();

    std::cout << "OpenGL Renderer: " << (char*)glGetString(GL_RENDERER) << std::endl;
    std::cout << "OpenGL Version: " << (char*)glGetString(GL_VERSION) << std::endl;

    IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG);

    Init();

    while (running)
    {
        SDL_Event event;
        while (SDL_PollEvent(&event))
        {
            if (event.type == SDL_EventType::SDL_QUIT)
            {
                running = false;
            }
        }

        Update();
        Display();

        SDL_GL_SwapWindow(window);
    }

    IMG_Quit();

    SDL_GL_DeleteContext(context);
    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;
}

void Init()
{
    shader.LoadFromFiles("Data/Diffuse.vert", "Data/Diffuse.frag");
    shader.Start();

    mesh.LoadObjFile("Data/Hallway.obj");

    texture.Load("Data/Hallway.png");

    material.SetShader(shader);
    material.SetTexture(shader.GetUniformLocation("tex_diffuse"), texture);

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);

    glClearColor(0.1f, 0.1f, 0.1f, 0.0f);

    SDL_SetRelativeMouseMode(SDL_TRUE);
}

void Update()
{
    input.Update();

    const float sensitivity = 0.2f;
    cameraRot.x -= sensitivity * input.GetRelativeMouseX();
    cameraRot.y = Math::Clamp(cameraRot.y - sensitivity * input.GetRelativeMouseY(), -90.0f, 90.0f);

    Quaternion rotation = Quaternion::AngleAxis(cameraRot.x, Vector3::up) * Quaternion::AngleAxis(cameraRot.y, Vector3::right);

    //Forward and back
    if (input.KeyDown(SDL_SCANCODE_W))
    {
        cameraPos += 0.1f * (rotation * Vector3::forward);
    }
    else if (input.KeyDown(SDL_SCANCODE_S))
    {
        cameraPos += 0.1f * (rotation * Vector3::back);
    }

    //Left and right
    if (input.KeyDown(SDL_SCANCODE_A))
    {
        cameraPos += 0.1f * (rotation * Vector3::left);
    }
    else if (input.KeyDown(SDL_SCANCODE_D))
    {
        cameraPos += 0.1f * (rotation * Vector3::right);
    }

    //Up and down
    if (input.KeyDown(SDL_SCANCODE_Q))
    {
        cameraPos += 0.1f * (rotation * Vector3::down);
    }
    else if (input.KeyDown(SDL_SCANCODE_E))
    {
        cameraPos += 0.1f * (rotation * Vector3::up);
    }
}

void Display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    auto projection = Matrix4x4::Perspective(60, 16.0f / 9.0f, 0.01f, 1000);
    auto view = Matrix4x4::FromTransform(
        cameraPos,
        Quaternion::AngleAxis(cameraRot.x, Vector3::up) * Quaternion::AngleAxis(cameraRot.y, Vector3::right),
        Vector3::one).GetInverse();
    auto matrix = projection * view * Matrix4x4::FromPosition(Vector3(0, 0, -4));
    glUniformMatrix4fv(shader.GetUniformLocation("in_modelview"), 1, false, &matrix[0]);

    material.Start();
    mesh.Draw();

    auto error = glGetError();
    if (error != GL_NO_ERROR)
    {
        std::cout << error << " : " << glewGetErrorString(error);
    }
}
<|endoftext|>


<commit_before>#include "MainWindow.h"

#include <QtGlobal>
#include <QTimer>
#include <QCoreApplication>
#include <QDateTime>
#include <QSettings>
#include <QDir>
#include <QDebug>

MainWindow::MainWindow() :
    m_root(NULL),
    m_camera(NULL),
    m_scene_manager(NULL),
    m_window(NULL),
    m_resources_config(Ogre::StringUtil::BLANK),
    m_camera_man(NULL),
    m_shut_down(false),
    m_input_manager(NULL),
    m_mouse(NULL),
    m_keyboard(NULL),
    m_server(NULL)
{
    loadControls();
}

MainWindow::~MainWindow()
{
    delete m_camera_man;

    // Remove ourself as a Window listener
    Ogre::WindowEventUtilities::removeWindowEventListener(m_window, this);
    windowClosed(m_window);
    delete m_root;
}

void MainWindow::loadControls()
{
    QDir dir(QCoreApplication::applicationDirPath());
    QSettings settings(dir.absoluteFilePath("mineflayer.ini"), QSettings::IniFormat);
    m_key_to_control.insert((OIS::KeyCode)settings.value("controls/forward", OIS::KC_W).toInt(), Forward);
    m_key_to_control.insert((OIS::KeyCode)settings.value("controls/back", OIS::KC_S).toInt(), Back);
    m_key_to_control.insert((OIS::KeyCode)settings.value("controls/left", OIS::KC_A).toInt(), Left);
    m_key_to_control.insert((OIS::KeyCode)settings.value("controls/right", OIS::KC_D).toInt(), Right);
    m_key_to_control.insert((OIS::KeyCode)settings.value("controls/jump", OIS::KC_SPACE).toInt(), Jump);
    m_key_to_control.insert((OIS::KeyCode)settings.value("controls/crouch", OIS::KC_Z).toInt(), Crouch);
    m_key_to_control.insert((OIS::KeyCode)settings.value("controls/discard_item", OIS::KC_Q).toInt(), DiscardItem);
    m_key_to_control.insert((OIS::KeyCode)settings.value("controls/action_1", OIS::KC_NUMPAD0).toInt(), Action1);
    m_key_to_control.insert((OIS::KeyCode)settings.value("controls/action_2", OIS::KC_NUMPAD1).toInt(), Action2);
    m_key_to_control.insert((OIS::KeyCode)settings.value("controls/inventory", OIS::KC_I).toInt(), Inventory);
    m_key_to_control.insert((OIS::KeyCode)settings.value("controls/chat", OIS::KC_T).toInt(), Chat);

    QHashIterator<OIS::KeyCode, Control> it(m_key_to_control);
    while (it.hasNext()) {
        it.next();
        m_control_to_key.insert(it.value(), it.key());
    }
}

bool MainWindow::configure()
{
    if (! m_root->restoreConfig()) {
        if (! m_root->showConfigDialog())
            return false;
    }
    m_window = m_root->initialise(true, "Mine Flayer");
    if (! m_window)
        return false;

    return true;
}

void MainWindow::createCamera()
{
    // Create the camera
    m_camera = m_scene_manager->createCamera("PlayerCam");

    // Position it at 500 in Z direction
    m_camera->setPosition(Ogre::Vector3(0,0,80));
    // Look back along -Z
    m_camera->lookAt(Ogre::Vector3(0,0,-300));
    m_camera->setNearClipDistance(5);

    m_camera_man = new OgreBites::SdkCameraMan(m_camera);   // create a default camera controller
}

void MainWindow::createFrameListener()
{
    Ogre::LogManager::getSingletonPtr()->logMessage("*** Initializing OIS ***");
    OIS::ParamList pl;
    size_t windowHnd = 0;
    std::ostringstream windowHndStr;

    m_window->getCustomAttribute("WINDOW", &windowHnd);
    windowHndStr << windowHnd;
    pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));

    m_input_manager = OIS::InputManager::createInputSystem( pl );

    m_keyboard = static_cast<OIS::Keyboard*>(m_input_manager->createInputObject( OIS::OISKeyboard, true ));
    m_mouse = static_cast<OIS::Mouse*>(m_input_manager->createInputObject( OIS::OISMouse, true ));

    m_mouse->setEventCallback(this);
    m_keyboard->setEventCallback(this);

    // Set initial mouse clipping size
    windowResized(m_window);

    // Register as a Window listener
    Ogre::WindowEventUtilities::addWindowEventListener(m_window, this);

    m_root->addFrameListener(this);
}

void MainWindow::createViewports()
{
    // Create one viewport, entire window
    Ogre::Viewport* vp = m_window->addViewport(m_camera);
    vp->setBackgroundColour(Ogre::ColourValue(0,0,0));

    // Alter the camera aspect ratio to match the viewport
    m_camera->setAspectRatio(
        Ogre::Real(vp->getActualWidth()) / Ogre::Real(vp->getActualHeight()));
}

void MainWindow::setupResources()
{
    Ogre::ResourceGroupManager * mgr = Ogre::ResourceGroupManager::getSingletonPtr();
    mgr->addResourceLocation("media", "FileSystem", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
}

void MainWindow::loadResources()
{
    Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    {
        // grab all the textures from resources
        //QImage terrain(":/textures/terrain.png");
        //terrain.convertToFormat(QImage::Format_ARGB32_Premultiplied);

        QFile texture_index_file(":/textures/textures.txt");
        texture_index_file.open(QFile::ReadOnly);
        QTextStream stream(&texture_index_file);
        while (! stream.atEnd()) {
            QString line = stream.readLine().trimmed();
            if (line.isEmpty() || line.startsWith("#"))
                continue;
            QStringList parts = line.split(QRegExp("\\s+"), QString::SkipEmptyParts);
            Q_ASSERT(parts.size() == 5);
            QString name = parts.at(0);
            int x = parts.at(1).toInt();
            int y = parts.at(2).toInt();
            int w = parts.at(3).toInt();
            int h = parts.at(4).toInt();
            //QImage image = terrain.copy(x, y, w, h).rgbSwapped();
            //Texture * texture = new Texture(image);
            //s_textures.insert(name, texture);
        }
        texture_index_file.close();
    }

    {
        // grab all the solid block data from resources
        QFile blocks_file(":/textures/blocks.txt");
        blocks_file.open(QFile::ReadOnly);
        QTextStream stream(&blocks_file);
        while(! stream.atEnd()) {
            QString line = stream.readLine().trimmed();
            if (line.isEmpty() || line.startsWith("#"))
                continue;
            QStringList parts = line.split(QRegExp("\\s+"), QString::SkipEmptyParts);
            Q_ASSERT(parts.size() == 8);
            int id = parts.at(0).toInt();
            QString name = parts.at(1);
            QString top = parts.at(2);
            QString bottom = parts.at(3);
            QString front = parts.at(4);
            QString back = parts.at(5);
            QString left = parts.at(6);
            QString right = parts.at(7);

//            Mesh * textured_cube = Mesh::createUnitCube(Constants::white,
//                s_textures.value(top),
//                s_textures.value(bottom),
//                s_textures.value(front),
//                s_textures.value(back),
//                s_textures.value(left),
//                s_textures.value(right));
//            s_meshes.replace(id, textured_cube);
        }
        blocks_file.close();
    }
}

void MainWindow::go()
{
    m_resources_config = "resources.cfg";

    if (!setup())
        return;

    m_root->startRendering();
}

bool MainWindow::setup()
{
    m_root = new Ogre::Root("resources/plugins.cfg");

    setupResources();

    bool carryOn = configure();
    if (!carryOn) return false;

    // Get the SceneManager, in this case a generic one
    m_scene_manager = m_root->createSceneManager(Ogre::ST_GENERIC);

    createCamera();
    createViewports();

    // Set default mipmap level (NB some APIs ignore this)
    Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);

    // Load resources
    loadResources();

    // create the scene
    m_scene_manager->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5));

    createFrameListener();

    return true;
};

bool MainWindow::frameRenderingQueued(const Ogre::FrameEvent& evt)
{
    if(m_window->isClosed())
        return false;

    if(m_shut_down)
        return false;

    //Need to capture/update each device
    m_keyboard->capture();
    m_mouse->capture();
    QCoreApplication::processEvents();

    // compute next frame

    m_camera_man->frameRenderingQueued(evt);   // if dialog isn't up, then update the camera

    return true;
}

bool MainWindow::keyPressed( const OIS::KeyEvent &arg )
{
    if (arg.key == OIS::KC_ESCAPE || (m_keyboard->isModifierDown(OIS::Keyboard::Alt) && arg.key == OIS::KC_F4))
        m_shut_down = true;

    m_camera_man->injectKeyDown(arg);
    return true;
}

bool MainWindow::keyReleased( const OIS::KeyEvent &arg )
{
    m_camera_man->injectKeyUp(arg);
    return true;
}

bool MainWindow::mouseMoved( const OIS::MouseEvent &arg )
{
    m_camera_man->injectMouseMove(arg);
    return true;
}

bool MainWindow::mousePressed( const OIS::MouseEvent &arg, OIS::MouseButtonID id )
{
    m_camera_man->injectMouseDown(arg, id);
    return true;
}

bool MainWindow::mouseReleased( const OIS::MouseEvent &arg, OIS::MouseButtonID id )
{
    m_camera_man->injectMouseUp(arg, id);
    return true;
}

void MainWindow::windowResized(Ogre::RenderWindow* rw)
{
    // Adjust mouse clipping area
    unsigned int width, height, depth;
    int left, top;
    rw->getMetrics(width, height, depth, left, top);

    const OIS::MouseState &ms = m_mouse->getMouseState();
    ms.width = width;
    ms.height = height;
}

void MainWindow::windowClosed(Ogre::RenderWindow* rw)
{
    // Unattach OIS before window shutdown (very important under Linux)
    // Only close for window that created OIS (the main window)
    if (rw == m_window && m_input_manager) {
        m_input_manager->destroyInputObject(m_mouse);
        m_input_manager->destroyInputObject(m_keyboard);

        OIS::InputManager::destroyInputSystem(m_input_manager);
        m_input_manager = NULL;
    }
}

void MainWindow::updateChunk(QSharedPointer<Chunk> chunk)
{

}
<commit_msg>suppressing Ogre debug output on stdout<commit_after>#include "MainWindow.h"

#include <QtGlobal>
#include <QTimer>
#include <QCoreApplication>
#include <QDateTime>
#include <QSettings>
#include <QDir>
#include <QDebug>

MainWindow::MainWindow() :
    m_root(NULL),
    m_camera(NULL),
    m_scene_manager(NULL),
    m_window(NULL),
    m_resources_config(Ogre::StringUtil::BLANK),
    m_camera_man(NULL),
    m_shut_down(false),
    m_input_manager(NULL),
    m_mouse(NULL),
    m_keyboard(NULL),
    m_server(NULL)
{
    loadControls();
}

MainWindow::~MainWindow()
{
    delete m_camera_man;

    // Remove ourself as a Window listener
    Ogre::WindowEventUtilities::removeWindowEventListener(m_window, this);
    windowClosed(m_window);
    delete m_root;
}

void MainWindow::loadControls()
{
    QDir dir(QCoreApplication::applicationDirPath());
    QSettings settings(dir.absoluteFilePath("mineflayer.ini"), QSettings::IniFormat);
    m_key_to_control.insert((OIS::KeyCode)settings.value("controls/forward", OIS::KC_W).toInt(), Forward);
    m_key_to_control.insert((OIS::KeyCode)settings.value("controls/back", OIS::KC_S).toInt(), Back);
    m_key_to_control.insert((OIS::KeyCode)settings.value("controls/left", OIS::KC_A).toInt(), Left);
    m_key_to_control.insert((OIS::KeyCode)settings.value("controls/right", OIS::KC_D).toInt(), Right);
    m_key_to_control.insert((OIS::KeyCode)settings.value("controls/jump", OIS::KC_SPACE).toInt(), Jump);
    m_key_to_control.insert((OIS::KeyCode)settings.value("controls/crouch", OIS::KC_Z).toInt(), Crouch);
    m_key_to_control.insert((OIS::KeyCode)settings.value("controls/discard_item", OIS::KC_Q).toInt(), DiscardItem);
    m_key_to_control.insert((OIS::KeyCode)settings.value("controls/action_1", OIS::KC_NUMPAD0).toInt(), Action1);
    m_key_to_control.insert((OIS::KeyCode)settings.value("controls/action_2", OIS::KC_NUMPAD1).toInt(), Action2);
    m_key_to_control.insert((OIS::KeyCode)settings.value("controls/inventory", OIS::KC_I).toInt(), Inventory);
    m_key_to_control.insert((OIS::KeyCode)settings.value("controls/chat", OIS::KC_T).toInt(), Chat);

    QHashIterator<OIS::KeyCode, Control> it(m_key_to_control);
    while (it.hasNext()) {
        it.next();
        m_control_to_key.insert(it.value(), it.key());
    }
}

bool MainWindow::configure()
{
    if (! m_root->restoreConfig()) {
        if (! m_root->showConfigDialog())
            return false;
    }
    m_window = m_root->initialise(true, "Mine Flayer");
    if (! m_window)
        return false;

    return true;
}

void MainWindow::createCamera()
{
    // Create the camera
    m_camera = m_scene_manager->createCamera("PlayerCam");

    // Position it at 500 in Z direction
    m_camera->setPosition(Ogre::Vector3(0,0,80));
    // Look back along -Z
    m_camera->lookAt(Ogre::Vector3(0,0,-300));
    m_camera->setNearClipDistance(5);

    m_camera_man = new OgreBites::SdkCameraMan(m_camera);   // create a default camera controller
}

void MainWindow::createFrameListener()
{
    Ogre::LogManager::getSingletonPtr()->logMessage("*** Initializing OIS ***");
    OIS::ParamList pl;
    size_t windowHnd = 0;
    std::ostringstream windowHndStr;

    m_window->getCustomAttribute("WINDOW", &windowHnd);
    windowHndStr << windowHnd;
    pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));

    m_input_manager = OIS::InputManager::createInputSystem( pl );

    m_keyboard = static_cast<OIS::Keyboard*>(m_input_manager->createInputObject( OIS::OISKeyboard, true ));
    m_mouse = static_cast<OIS::Mouse*>(m_input_manager->createInputObject( OIS::OISMouse, true ));

    m_mouse->setEventCallback(this);
    m_keyboard->setEventCallback(this);

    // Set initial mouse clipping size
    windowResized(m_window);

    // Register as a Window listener
    Ogre::WindowEventUtilities::addWindowEventListener(m_window, this);

    m_root->addFrameListener(this);
}

void MainWindow::createViewports()
{
    // Create one viewport, entire window
    Ogre::Viewport* vp = m_window->addViewport(m_camera);
    vp->setBackgroundColour(Ogre::ColourValue(0,0,0));

    // Alter the camera aspect ratio to match the viewport
    m_camera->setAspectRatio(
        Ogre::Real(vp->getActualWidth()) / Ogre::Real(vp->getActualHeight()));
}

void MainWindow::setupResources()
{
    Ogre::ResourceGroupManager * mgr = Ogre::ResourceGroupManager::getSingletonPtr();
    mgr->addResourceLocation("media", "FileSystem", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
}

void MainWindow::loadResources()
{
    Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    {
        // grab all the textures from resources
        //QImage terrain(":/textures/terrain.png");
        //terrain.convertToFormat(QImage::Format_ARGB32_Premultiplied);

        QFile texture_index_file(":/textures/textures.txt");
        texture_index_file.open(QFile::ReadOnly);
        QTextStream stream(&texture_index_file);
        while (! stream.atEnd()) {
            QString line = stream.readLine().trimmed();
            if (line.isEmpty() || line.startsWith("#"))
                continue;
            QStringList parts = line.split(QRegExp("\\s+"), QString::SkipEmptyParts);
            Q_ASSERT(parts.size() == 5);
            QString name = parts.at(0);
            int x = parts.at(1).toInt();
            int y = parts.at(2).toInt();
            int w = parts.at(3).toInt();
            int h = parts.at(4).toInt();
            //QImage image = terrain.copy(x, y, w, h).rgbSwapped();
            //Texture * texture = new Texture(image);
            //s_textures.insert(name, texture);
        }
        texture_index_file.close();
    }

    {
        // grab all the solid block data from resources
        QFile blocks_file(":/textures/blocks.txt");
        blocks_file.open(QFile::ReadOnly);
        QTextStream stream(&blocks_file);
        while(! stream.atEnd()) {
            QString line = stream.readLine().trimmed();
            if (line.isEmpty() || line.startsWith("#"))
                continue;
            QStringList parts = line.split(QRegExp("\\s+"), QString::SkipEmptyParts);
            Q_ASSERT(parts.size() == 8);
            int id = parts.at(0).toInt();
            QString name = parts.at(1);
            QString top = parts.at(2);
            QString bottom = parts.at(3);
            QString front = parts.at(4);
            QString back = parts.at(5);
            QString left = parts.at(6);
            QString right = parts.at(7);

//            Mesh * textured_cube = Mesh::createUnitCube(Constants::white,
//                s_textures.value(top),
//                s_textures.value(bottom),
//                s_textures.value(front),
//                s_textures.value(back),
//                s_textures.value(left),
//                s_textures.value(right));
//            s_meshes.replace(id, textured_cube);
        }
        blocks_file.close();
    }
}

void MainWindow::go()
{
    m_resources_config = "resources.cfg";

    if (!setup())
        return;

    m_root->startRendering();
}

bool MainWindow::setup()
{
    // suppress debug output on stdout
    Ogre::LogManager * logManager = new Ogre::LogManager;
    logManager->createLog("DefaultLog", true, false, false);

    m_root = new Ogre::Root("resources/plugins.cfg");

    setupResources();

    bool carryOn = configure();
    if (!carryOn) return false;

    // Get the SceneManager, in this case a generic one
    m_scene_manager = m_root->createSceneManager(Ogre::ST_GENERIC);

    createCamera();
    createViewports();

    // Set default mipmap level (NB some APIs ignore this)
    Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);

    // Load resources
    loadResources();

    // create the scene
    m_scene_manager->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5));

    createFrameListener();

    return true;
};

bool MainWindow::frameRenderingQueued(const Ogre::FrameEvent& evt)
{
    if(m_window->isClosed())
        return false;

    if(m_shut_down)
        return false;

    //Need to capture/update each device
    m_keyboard->capture();
    m_mouse->capture();
    QCoreApplication::processEvents();

    // compute next frame

    m_camera_man->frameRenderingQueued(evt);   // if dialog isn't up, then update the camera

    return true;
}

bool MainWindow::keyPressed( const OIS::KeyEvent &arg )
{
    if (arg.key == OIS::KC_ESCAPE || (m_keyboard->isModifierDown(OIS::Keyboard::Alt) && arg.key == OIS::KC_F4))
        m_shut_down = true;

    m_camera_man->injectKeyDown(arg);
    return true;
}

bool MainWindow::keyReleased( const OIS::KeyEvent &arg )
{
    m_camera_man->injectKeyUp(arg);
    return true;
}

bool MainWindow::mouseMoved( const OIS::MouseEvent &arg )
{
    m_camera_man->injectMouseMove(arg);
    return true;
}

bool MainWindow::mousePressed( const OIS::MouseEvent &arg, OIS::MouseButtonID id )
{
    m_camera_man->injectMouseDown(arg, id);
    return true;
}

bool MainWindow::mouseReleased( const OIS::MouseEvent &arg, OIS::MouseButtonID id )
{
    m_camera_man->injectMouseUp(arg, id);
    return true;
}

void MainWindow::windowResized(Ogre::RenderWindow* rw)
{
    // Adjust mouse clipping area
    unsigned int width, height, depth;
    int left, top;
    rw->getMetrics(width, height, depth, left, top);

    const OIS::MouseState &ms = m_mouse->getMouseState();
    ms.width = width;
    ms.height = height;
}

void MainWindow::windowClosed(Ogre::RenderWindow* rw)
{
    // Unattach OIS before window shutdown (very important under Linux)
    // Only close for window that created OIS (the main window)
    if (rw == m_window && m_input_manager) {
        m_input_manager->destroyInputObject(m_mouse);
        m_input_manager->destroyInputObject(m_keyboard);

        OIS::InputManager::destroyInputSystem(m_input_manager);
        m_input_manager = NULL;
    }
}

void MainWindow::updateChunk(QSharedPointer<Chunk> chunk)
{

}
<|endoftext|>


<commit_before>#include "MainWindow.h"
#include "ui_MainWindow.h"

#include "config.h"
#include "Downloader.h"
#include "SubtitleLanguage.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    m_destDir(defaultDestDir()),
    m_updateChecker(new UpdateChecker(this)),
    m_downloader(NULL),
    m_downloadInProgress(false),
    m_exitOnSuccess(false)
{
    QDir savedDir = m_settings.value("destDir", m_destDir.absolutePath()).toString();
    if (savedDir.exists()) {
        m_destDir = savedDir;
    }

    ui->setupUi(this);

    this->setWindowTitle(this->windowTitle() + " " + tr("(v%1)").arg(YLE_DOWNLOADER_GUI_VERSION));

    initSubtitlesComboBox();

    updateDestDirLabel();
    ui->statusLabel->setText("");
    ui->downloadButton->setEnabled(false);
    ui->cancelButton->setVisible(false);
    ui->detailsWidget->setVisible(false);
    ui->updateLabel->setVisible(false);

    layout()->setSizeConstraint(QLayout::SetFixedSize);

    m_videoTableModel = new VideoTableModel();
    if (m_videoTableModel) {
        ui->videoTableView->setModel(m_videoTableModel);
    }
    m_currentlyDownloadingVideoRow = -1;

#ifdef Q_WS_WIN
    m_resumeDownload = false;
#else
    m_resumeDownload = true;
#endif

    m_videoTableEditTriggers = (const QFlags<QAbstractItemView::EditTrigger>)(QAbstractItemView::AllEditTriggers & ~QAbstractItemView::CurrentChanged);
    ui->videoTableView->setEditTriggers(m_videoTableEditTriggers);
    ui->videoTableView->setFocus(Qt::OtherFocusReason);

    setAcceptDrops(true);

    connect(m_videoTableModel, SIGNAL(rowsRemoved(QModelIndex, int, int)),
            ui->videoTableView, SLOT(rowsRemoved(QModelIndex, int, int)));

    connect(m_videoTableModel, SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(videoTableChanged()));
    connect(m_videoTableModel, SIGNAL(rowsRemoved(QModelIndex, int, int)), this, SLOT(videoTableChanged()));

    connect(ui->destDirButton, SIGNAL(clicked()), this, SLOT(chooseDestDir()));
    connect(ui->downloadButton, SIGNAL(clicked()), this, SLOT(startDownload()));

    connect(ui->cancelButton, SIGNAL(clicked()), this, SLOT(cancelRequested()));

    connect(ui->detailsButton, SIGNAL(toggled(bool)), ui->detailsWidget, SLOT(setVisible(bool)));

    connect(m_updateChecker, SIGNAL(updateAvailable(QString,QUrl)), this, SLOT(updateAvailable(QString,QUrl)));
    connect(ui->updateLabel, SIGNAL(linkActivated(QString)), this, SLOT(openUrl(QString)));
}

MainWindow::~MainWindow()
{
    delete ui;
    delete m_videoTableModel;
}

void MainWindow::startDownloadFrom(QString url)
{
    if (m_videoTableModel->insertRow(0)) {
        QModelIndex index = m_videoTableModel->index(0, VideoTableModel::UrlColumn);
        if (m_videoTableModel->setData(index, url, Qt::EditRole)) {
            startDownload();
        }
    }
}

void MainWindow::chooseDestDir()
{
    QString newDir = QFileDialog::getExistingDirectory(this, tr("Choose download folder"), m_destDir.absolutePath());
    if (!newDir.isNull()) {
        m_destDir = QDir(newDir);
        m_settings.setValue("destDir", newDir);
        updateDestDirLabel();
    }
}

void MainWindow::saveSubtitlesChoice()
{
    m_settings.setValue("subtitles", ui->subtitlesComboBox->itemData(ui->subtitlesComboBox->currentIndex()));
}

void MainWindow::videoTableChanged()
{
    if (!m_downloadInProgress) {
        ui->downloadButton->setEnabled(m_videoTableModel->videoCount() > 0);
    }
}

void MainWindow::startDownload()
{
    Q_ASSERT(!m_downloadInProgress);

    if (m_videoTableModel->videoCount() <= 0) {
        qWarning() << "Attempt to start download with nothing to download.";
        return;
    }
    ui->detailsTextEdit->clear();
    setDownloadWidgetsDisabled(true);
    ui->cancelButton->setVisible(true);

    m_currentlyDownloadingVideoRow = -1;
    startNextDownload();
}

void MainWindow::startNextDownload() {
    m_currentlyDownloadingVideoRow++;
    if (m_currentlyDownloadingVideoRow >= (m_videoTableModel->videoCount())) {
        downloadEnded();
        return;
    }

    if (m_downloader) {
        m_downloader->deleteLater();
        m_downloader = NULL;
    }

    QUrl url = QUrl(m_videoTableModel->url(this->m_currentlyDownloadingVideoRow));

    QStringList yleDlExtraOptions = ui->yleDlExtraOptionsLineEdit->text().trimmed().split(" ", QString::SkipEmptyParts);
    QStringList extraArgs;
    foreach (QString str, yleDlExtraOptions) {
        if (str.startsWith("-")) {
            extraArgs.append(str);
        }
    }
    if (m_resumeDownload) {
        extraArgs.append(QString("-e"));
    }

    m_downloader = new Downloader(url, m_destDir, this);
    m_downloader->setExtraArgs(extraArgs);

    QString subtitlesOption = ui->subtitlesComboBox->itemData(ui->subtitlesComboBox->currentIndex()).toString();
    m_downloader->setSubtitles(subtitlesOption);

    connect(m_downloader, SIGNAL(downloadSucceeded()), this, SLOT(downloadSucceeded()));
    connect(m_downloader, SIGNAL(downloadCanceled()), this, SLOT(downloadCanceled()));
    connect(m_downloader, SIGNAL(downloadFailed()), this, SLOT(downloadFailed()));

    connect(m_downloader, SIGNAL(downloadFileCreated(QString)), this, SLOT(reportDestFileName(QString)));
    connect(m_downloader, SIGNAL(downloadProgress(int)), this, SLOT(reportProgress(int)));
    connect(m_downloader, SIGNAL(downloadUnknownProgress(double)), this, SLOT(reportUnknownProgress(double)));
    connect(m_downloader, SIGNAL(downloaderOutputWritten(QString)), this, SLOT(downloaderOutputWritten(QString)));

    m_videoTableModel->setUnknownDownloadProgress(this->m_currentlyDownloadingVideoRow, "");
    m_videoTableModel->setDownloadState(this->m_currentlyDownloadingVideoRow,
        VideoInfo::StateStarting);

    m_downloadInProgress = true;
    m_downloader->start();
}

void MainWindow::reportDestFileName(QString name)
{
    m_destFileName = name;
    ui->statusLabel->setText(tr("Downloading to file %1").arg(name));
}

void MainWindow::reportProgress(int percentage)
{
    m_videoTableModel->setKnownDownloadProgress(this->m_currentlyDownloadingVideoRow,
        percentage);
    m_videoTableModel->setDownloadState(this->m_currentlyDownloadingVideoRow,
        VideoInfo::StateLoading);
}

void MainWindow::reportUnknownProgress(double secondsDownloaded)
{
    QString progressStr = formatSecondsDownloaded(secondsDownloaded);
    m_videoTableModel->setUnknownDownloadProgress(this->m_currentlyDownloadingVideoRow,
        progressStr);
    m_videoTableModel->setDownloadState(this->m_currentlyDownloadingVideoRow,
        VideoInfo::StateLoading);
}

void MainWindow::downloaderOutputWritten(QString line)
{
    ui->detailsTextEdit->appendPlainText(line);
}

void MainWindow::downloadSucceeded()
{
    m_videoTableModel->setKnownDownloadProgress(this->m_currentlyDownloadingVideoRow, 100);
    m_videoTableModel->setDownloadState(this->m_currentlyDownloadingVideoRow,
        VideoInfo::StateLoadedOk);

    this->startNextDownload();
}

void MainWindow::downloadCanceled()
{
    if (m_videoTableModel->downloadProgress(this->m_currentlyDownloadingVideoRow) == -1) {
        m_videoTableModel->setKnownDownloadProgress(this->m_currentlyDownloadingVideoRow, 0, false);
    }
    m_videoTableModel->setDownloadState(this->m_currentlyDownloadingVideoRow,
        VideoInfo::StateCanceled);

    this->downloadEnded();
}

void MainWindow::downloadFailed()
{
    if (m_videoTableModel->downloadProgress(this->m_currentlyDownloadingVideoRow) == -1) {
        m_videoTableModel->setKnownDownloadProgress(this->m_currentlyDownloadingVideoRow, 0, false);
    }
    m_videoTableModel->setDownloadState(this->m_currentlyDownloadingVideoRow,
        VideoInfo::StateFailed);

    this->startNextDownload();
}

void MainWindow::cancelRequested()
{
    if (m_downloadInProgress) {
        if (confirmCancel()) {
            if (m_downloadInProgress) {
                m_downloader->cancel();
            } else {
                qWarning() << "Download finished while confirming cancel.";
            }
        }
    } else {
        qWarning() << "Cancel requested while no download in progress.";
    }
}

void MainWindow::updateAvailable(QString version, QUrl url)
{
    QString text = tr("An updated downloader (v%1) is available:
%2")
            .arg(version)
            .arg(Qt::escape(url.toString()));
    ui->updateLabel->setText(text);
    ui->updateLabel->setVisible(true);
}

void MainWindow::openUrl(QString url)
{
    QDesktopServices::openUrl(QUrl(url));
}

void MainWindow::closeEvent(QCloseEvent* event)
{
    if (m_downloadInProgress) {
        if (confirmCancel()) {
            event->accept();
        } else {
            event->ignore();
        }
    }
}

void MainWindow::showEvent(QShowEvent *event)
{
    Q_UNUSED(event)
    updateVideoTableView();
}

void MainWindow::dragEnterEvent(QDragEnterEvent* event) {
    if (event->mimeData()->hasText()) {
        event->acceptProposedAction();
    }
}

void MainWindow::dropEvent(QDropEvent* event) {
    m_videoTableModel->addUrl(event->mimeData()->text());
    event->acceptProposedAction();
}

void MainWindow::initSubtitlesComboBox()
{
    foreach (SubtitleLanguage lang, SubtitleLanguage::getAll()) {
        ui->subtitlesComboBox->addItem(lang.displayName(), lang.optionId());
    }

    QString defaultOption = m_settings.value("subtitles", SubtitleLanguage::getDefault().optionId()).toString();
    int defaultOptionIndex = ui->subtitlesComboBox->findData(defaultOption);
    if (defaultOptionIndex != -1) {
        ui->subtitlesComboBox->setCurrentIndex(defaultOptionIndex);
    }

    connect(ui->subtitlesComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(saveSubtitlesChoice()));
}

bool MainWindow::confirmCancel()
{
    QMessageBox::StandardButton choice =
            QMessageBox::question(this,
                                  this->windowTitle(),
                                  tr("Really cancel download?"),
                                  QMessageBox::Yes | QMessageBox::No,
                                  QMessageBox::Yes);

    return (choice == QMessageBox::Yes);
}

void MainWindow::downloadEnded()
{
    m_downloadInProgress = false;

    setDownloadWidgetsDisabled(false);

    ui->cancelButton->setVisible(false);
    ui->statusLabel->setText("");

    m_updateChecker->checkForUpdate();
}

void MainWindow::setDownloadWidgetsDisabled(bool disabled)
{
    ui->destDirButton->setDisabled(disabled);
    ui->yleDlExtraOptionsLineEdit->setDisabled(disabled);
    ui->downloadButton->setDisabled(disabled);
    ui->subtitlesComboBox->setDisabled(disabled);
    ui->yleDlExtraOptionsLineEdit->setDisabled(disabled);
    // Don't disable videoTableView because text will go gray. Instead,
    // disable editing.
    if (disabled) {
        ui->videoTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    } else {
        ui->videoTableView->setEditTriggers(m_videoTableEditTriggers);
    }
}

void MainWindow::updateDestDirLabel()
{
    QString folder = QDir::toNativeSeparators(m_destDir.absolutePath());
    ui->destDirLabel->setText(tr("Download folder: %1").arg(folder));
}

void MainWindow::updateVideoTableView()
{
    int urlTableWidth = ui->videoTableView->viewport()->width();
    ui->videoTableView->setColumnWidth(VideoTableModel::UrlColumn, (urlTableWidth * 3)/5);
    ui->videoTableView->setColumnWidth(VideoTableModel::ProgressColumn, urlTableWidth / 5);
    ui->videoTableView->setColumnWidth(VideoTableModel::StatusColumn, urlTableWidth / 5);
}

QString MainWindow::formatSecondsDownloaded(double secondsDownloaded)
{
    int seconds = secondsDownloaded;
    int minutes = seconds / 60;
    seconds = seconds % 60;
    if (minutes > 0) {
        return tr("%1 min %2 sec").arg(minutes, 2).arg(seconds, 2);
    } else {
        return tr("%1 sec").arg(seconds);
    }
}

QDir MainWindow::defaultDestDir()
{
    QDir dir = QDir::home();
    QStringList dlDirs = QStringList();
    dlDirs += "Downloads";
    dlDirs += "Download";
    dlDirs += tr("Downloads");
    dlDirs += tr("Download");
    dlDirs += "downloads";
    dlDirs += "download";
    dlDirs += tr("downloads");
    dlDirs += tr("download");
    dlDirs += "Desktop";
    foreach (QString dlDir, dlDirs) {
        if (dir.cd(dlDir)) {
            break;
        }
    }
    return dir;
}
<commit_msg>Added proper download canceling on quit<commit_after>#include "MainWindow.h"
#include "ui_MainWindow.h"

#include "config.h"
#include "Downloader.h"
#include "SubtitleLanguage.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    m_destDir(defaultDestDir()),
    m_updateChecker(new UpdateChecker(this)),
    m_downloader(NULL),
    m_downloadInProgress(false),
    m_exitOnSuccess(false)
{
    QDir savedDir = m_settings.value("destDir", m_destDir.absolutePath()).toString();
    if (savedDir.exists()) {
        m_destDir = savedDir;
    }

    ui->setupUi(this);

    this->setWindowTitle(this->windowTitle() + " " + tr("(v%1)").arg(YLE_DOWNLOADER_GUI_VERSION));

    initSubtitlesComboBox();

    updateDestDirLabel();
    ui->statusLabel->setText("");
    ui->downloadButton->setEnabled(false);
    ui->cancelButton->setVisible(false);
    ui->detailsWidget->setVisible(false);
    ui->updateLabel->setVisible(false);

    layout()->setSizeConstraint(QLayout::SetFixedSize);

    m_videoTableModel = new VideoTableModel();
    if (m_videoTableModel) {
        ui->videoTableView->setModel(m_videoTableModel);
    }
    m_currentlyDownloadingVideoRow = -1;

#ifdef Q_WS_WIN
    m_resumeDownload = false;
#else
    m_resumeDownload = true;
#endif

    m_videoTableEditTriggers = (const QFlags<QAbstractItemView::EditTrigger>)(QAbstractItemView::AllEditTriggers & ~QAbstractItemView::CurrentChanged);
    ui->videoTableView->setEditTriggers(m_videoTableEditTriggers);
    ui->videoTableView->setFocus(Qt::OtherFocusReason);

    setAcceptDrops(true);

    connect(m_videoTableModel, SIGNAL(rowsRemoved(QModelIndex, int, int)),
            ui->videoTableView, SLOT(rowsRemoved(QModelIndex, int, int)));

    connect(m_videoTableModel, SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(videoTableChanged()));
    connect(m_videoTableModel, SIGNAL(rowsRemoved(QModelIndex, int, int)), this, SLOT(videoTableChanged()));

    connect(ui->destDirButton, SIGNAL(clicked()), this, SLOT(chooseDestDir()));
    connect(ui->downloadButton, SIGNAL(clicked()), this, SLOT(startDownload()));

    connect(ui->cancelButton, SIGNAL(clicked()), this, SLOT(cancelRequested()));

    connect(ui->detailsButton, SIGNAL(toggled(bool)), ui->detailsWidget, SLOT(setVisible(bool)));

    connect(m_updateChecker, SIGNAL(updateAvailable(QString,QUrl)), this, SLOT(updateAvailable(QString,QUrl)));
    connect(ui->updateLabel, SIGNAL(linkActivated(QString)), this, SLOT(openUrl(QString)));
}

MainWindow::~MainWindow()
{
    delete ui;
    delete m_videoTableModel;
}

void MainWindow::startDownloadFrom(QString url)
{
    if (m_videoTableModel->insertRow(0)) {
        QModelIndex index = m_videoTableModel->index(0, VideoTableModel::UrlColumn);
        if (m_videoTableModel->setData(index, url, Qt::EditRole)) {
            startDownload();
        }
    }
}

void MainWindow::chooseDestDir()
{
    QString newDir = QFileDialog::getExistingDirectory(this, tr("Choose download folder"), m_destDir.absolutePath());
    if (!newDir.isNull()) {
        m_destDir = QDir(newDir);
        m_settings.setValue("destDir", newDir);
        updateDestDirLabel();
    }
}

void MainWindow::saveSubtitlesChoice()
{
    m_settings.setValue("subtitles", ui->subtitlesComboBox->itemData(ui->subtitlesComboBox->currentIndex()));
}

void MainWindow::videoTableChanged()
{
    if (!m_downloadInProgress) {
        ui->downloadButton->setEnabled(m_videoTableModel->videoCount() > 0);
    }
}

void MainWindow::startDownload()
{
    Q_ASSERT(!m_downloadInProgress);

    if (m_videoTableModel->videoCount() <= 0) {
        qWarning() << "Attempt to start download with nothing to download.";
        return;
    }
    ui->detailsTextEdit->clear();
    setDownloadWidgetsDisabled(true);
    ui->cancelButton->setVisible(true);

    m_currentlyDownloadingVideoRow = -1;
    startNextDownload();
}

void MainWindow::startNextDownload() {
    m_currentlyDownloadingVideoRow++;
    if (m_currentlyDownloadingVideoRow >= (m_videoTableModel->videoCount())) {
        downloadEnded();
        return;
    }

    if (m_downloader) {
        m_downloader->deleteLater();
        m_downloader = NULL;
    }

    QUrl url = QUrl(m_videoTableModel->url(this->m_currentlyDownloadingVideoRow));

    QStringList yleDlExtraOptions = ui->yleDlExtraOptionsLineEdit->text().trimmed().split(" ", QString::SkipEmptyParts);
    QStringList extraArgs;
    foreach (QString str, yleDlExtraOptions) {
        if (str.startsWith("-")) {
            extraArgs.append(str);
        }
    }
    if (m_resumeDownload) {
        extraArgs.append(QString("-e"));
    }

    m_downloader = new Downloader(url, m_destDir, this);
    m_downloader->setExtraArgs(extraArgs);

    QString subtitlesOption = ui->subtitlesComboBox->itemData(ui->subtitlesComboBox->currentIndex()).toString();
    m_downloader->setSubtitles(subtitlesOption);

    connect(m_downloader, SIGNAL(downloadSucceeded()), this, SLOT(downloadSucceeded()));
    connect(m_downloader, SIGNAL(downloadCanceled()), this, SLOT(downloadCanceled()));
    connect(m_downloader, SIGNAL(downloadFailed()), this, SLOT(downloadFailed()));

    connect(m_downloader, SIGNAL(downloadFileCreated(QString)), this, SLOT(reportDestFileName(QString)));
    connect(m_downloader, SIGNAL(downloadProgress(int)), this, SLOT(reportProgress(int)));
    connect(m_downloader, SIGNAL(downloadUnknownProgress(double)), this, SLOT(reportUnknownProgress(double)));
    connect(m_downloader, SIGNAL(downloaderOutputWritten(QString)), this, SLOT(downloaderOutputWritten(QString)));

    m_videoTableModel->setUnknownDownloadProgress(this->m_currentlyDownloadingVideoRow, "");
    m_videoTableModel->setDownloadState(this->m_currentlyDownloadingVideoRow,
        VideoInfo::StateStarting);

    m_downloadInProgress = true;
    m_downloader->start();
}

void MainWindow::reportDestFileName(QString name)
{
    m_destFileName = name;
    ui->statusLabel->setText(tr("Downloading to file %1").arg(name));
}

void MainWindow::reportProgress(int percentage)
{
    m_videoTableModel->setKnownDownloadProgress(this->m_currentlyDownloadingVideoRow,
        percentage);
    m_videoTableModel->setDownloadState(this->m_currentlyDownloadingVideoRow,
        VideoInfo::StateLoading);
}

void MainWindow::reportUnknownProgress(double secondsDownloaded)
{
    QString progressStr = formatSecondsDownloaded(secondsDownloaded);
    m_videoTableModel->setUnknownDownloadProgress(this->m_currentlyDownloadingVideoRow,
        progressStr);
    m_videoTableModel->setDownloadState(this->m_currentlyDownloadingVideoRow,
        VideoInfo::StateLoading);
}

void MainWindow::downloaderOutputWritten(QString line)
{
    ui->detailsTextEdit->appendPlainText(line);
}

void MainWindow::downloadSucceeded()
{
    m_videoTableModel->setKnownDownloadProgress(this->m_currentlyDownloadingVideoRow, 100);
    m_videoTableModel->setDownloadState(this->m_currentlyDownloadingVideoRow,
        VideoInfo::StateLoadedOk);

    this->startNextDownload();
}

void MainWindow::downloadCanceled()
{
    if (m_videoTableModel->downloadProgress(this->m_currentlyDownloadingVideoRow) == -1) {
        m_videoTableModel->setKnownDownloadProgress(this->m_currentlyDownloadingVideoRow, 0, false);
    }
    m_videoTableModel->setDownloadState(this->m_currentlyDownloadingVideoRow,
        VideoInfo::StateCanceled);

    this->downloadEnded();
}

void MainWindow::downloadFailed()
{
    if (m_videoTableModel->downloadProgress(this->m_currentlyDownloadingVideoRow) == -1) {
        m_videoTableModel->setKnownDownloadProgress(this->m_currentlyDownloadingVideoRow, 0, false);
    }
    m_videoTableModel->setDownloadState(this->m_currentlyDownloadingVideoRow,
        VideoInfo::StateFailed);

    this->startNextDownload();
}

void MainWindow::cancelRequested()
{
    if (m_downloadInProgress) {
        if (confirmCancel()) {
            if (m_downloadInProgress) {
                m_downloader->cancel();
            } else {
                qWarning() << "Download finished while confirming cancel.";
            }
        }
    } else {
        qWarning() << "Cancel requested while no download in progress.";
    }
}

void MainWindow::updateAvailable(QString version, QUrl url)
{
    QString text = tr("An updated downloader (v%1) is available:
%2")
            .arg(version)
            .arg(Qt::escape(url.toString()));
    ui->updateLabel->setText(text);
    ui->updateLabel->setVisible(true);
}

void MainWindow::openUrl(QString url)
{
    QDesktopServices::openUrl(QUrl(url));
}

void MainWindow::closeEvent(QCloseEvent* event)
{
    if (m_downloadInProgress) {
        if (confirmCancel()) {
            if (m_downloadInProgress) {
                m_downloader->cancel();
            }
            event->accept();
        } else {
            event->ignore();
        }
    }
}

void MainWindow::showEvent(QShowEvent *event)
{
    Q_UNUSED(event)
    updateVideoTableView();
}

void MainWindow::dragEnterEvent(QDragEnterEvent* event) {
    if (event->mimeData()->hasText()) {
        event->acceptProposedAction();
    }
}

void MainWindow::dropEvent(QDropEvent* event) {
    m_videoTableModel->addUrl(event->mimeData()->text());
    event->acceptProposedAction();
}

void MainWindow::initSubtitlesComboBox()
{
    foreach (SubtitleLanguage lang, SubtitleLanguage::getAll()) {
        ui->subtitlesComboBox->addItem(lang.displayName(), lang.optionId());
    }

    QString defaultOption = m_settings.value("subtitles", SubtitleLanguage::getDefault().optionId()).toString();
    int defaultOptionIndex = ui->subtitlesComboBox->findData(defaultOption);
    if (defaultOptionIndex != -1) {
        ui->subtitlesComboBox->setCurrentIndex(defaultOptionIndex);
    }

    connect(ui->subtitlesComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(saveSubtitlesChoice()));
}

bool MainWindow::confirmCancel()
{
    QMessageBox::StandardButton choice =
            QMessageBox::question(this,
                                  this->windowTitle(),
                                  tr("Really cancel download?"),
                                  QMessageBox::Yes | QMessageBox::No,
                                  QMessageBox::Yes);

    return (choice == QMessageBox::Yes);
}

void MainWindow::downloadEnded()
{
    m_downloadInProgress = false;

    setDownloadWidgetsDisabled(false);

    ui->cancelButton->setVisible(false);
    ui->statusLabel->setText("");

    m_updateChecker->checkForUpdate();
}

void MainWindow::setDownloadWidgetsDisabled(bool disabled)
{
    ui->destDirButton->setDisabled(disabled);
    ui->yleDlExtraOptionsLineEdit->setDisabled(disabled);
    ui->downloadButton->setDisabled(disabled);
    ui->subtitlesComboBox->setDisabled(disabled);
    ui->yleDlExtraOptionsLineEdit->setDisabled(disabled);
    // Don't disable videoTableView because text will go gray. Instead,
    // disable editing.
    if (disabled) {
        ui->videoTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    } else {
        ui->videoTableView->setEditTriggers(m_videoTableEditTriggers);
    }
}

void MainWindow::updateDestDirLabel()
{
    QString folder = QDir::toNativeSeparators(m_destDir.absolutePath());
    ui->destDirLabel->setText(tr("Download folder: %1").arg(folder));
}

void MainWindow::updateVideoTableView()
{
    int urlTableWidth = ui->videoTableView->viewport()->width();
    ui->videoTableView->setColumnWidth(VideoTableModel::UrlColumn, (urlTableWidth * 3)/5);
    ui->videoTableView->setColumnWidth(VideoTableModel::ProgressColumn, urlTableWidth / 5);
    ui->videoTableView->setColumnWidth(VideoTableModel::StatusColumn, urlTableWidth / 5);
}

QString MainWindow::formatSecondsDownloaded(double secondsDownloaded)
{
    int seconds = secondsDownloaded;
    int minutes = seconds / 60;
    seconds = seconds % 60;
    if (minutes > 0) {
        return tr("%1 min %2 sec").arg(minutes, 2).arg(seconds, 2);
    } else {
        return tr("%1 sec").arg(seconds);
    }
}

QDir MainWindow::defaultDestDir()
{
    QDir dir = QDir::home();
    QStringList dlDirs = QStringList();
    dlDirs += "Downloads";
    dlDirs += "Download";
    dlDirs += tr("Downloads");
    dlDirs += tr("Download");
    dlDirs += "downloads";
    dlDirs += "download";
    dlDirs += tr("downloads");
    dlDirs += tr("download");
    dlDirs += "Desktop";
    foreach (QString dlDir, dlDirs) {
        if (dir.cd(dlDir)) {
            break;
        }
    }
    return dir;
}
<|endoftext|>