<commit_before>
#include <gameplay/GameplayModule.hpp>

#include <stdio.h>
#include <string.h>

#include <unistd.h>
#include <fcntl.h>
#include <assert.h>
#include <signal.h>

#include <QApplication>
#include <QFile>
#include <QDir>
#include <QDateTime>
 #include <QString>
#include <QMessageBox>

#include "MainWindow.hpp"
#include "Configuration.hpp"

using namespace   std;

//  we use this to catch Ctrl+C and kill the program
void signal_handler(  int signum) { exit(signum); }

void usage(  const char   * prog) {
    fprintf(stderr, "usage: %s [options...]\n", prog);
    fprintf(stderr, "\t-y:          run as the yellow team\n");
    fprintf(stderr, "\t-b:          run as the blue team\n");
    fprintf(stderr, "\t-c <file>:   specify the configuration file\n");
    fprintf(stderr, "\t-s <seed>:   set random seed (hexadecimal)\n");
    fprintf(stderr,
            "\t-pbk <file>: playbook file name as contained in "
            "'soccer/gameplay/playbooks/'\n");
    fprintf(stderr, "\t-ng:         no goalie\n");
    fprintf(stderr, "\t-sim:        use simulator\n");
    fprintf(stderr, "\t-freq:       specify radio frequency (906 or 904)\n");
    fprintf(stderr, "\t-nolog:      don't write log files\n");
    fprintf(stderr, "\t-noref:      don't use external referee commands\n");
    exit(1);
}

int main(int argc, char* argv[]) {
    printf("Starting Soccer...\n");

    //  register our signal handler
    signal(SIGINT, signal_handler);

    // Seed the large random number generator
    long int seed = 0;
    int fd = open("/dev/random", O_RDONLY);
    if (fd >= 0) {
        if (read(fd, &seed, sizeof(seed)) != sizeof(seed)) {
            fprintf(stderr, "Can't read /dev/random, using zero seed: %m\n");
        }
        close(fd);
    } else {
        fprintf(stderr, "Can't open /dev/random, using zero seed: %m\n");
    }

    QApplication app(argc, argv);

    bool blueTeam = false;
    QString cfgFile;
    vector<const char*> playDirs;
    bool sim = false;
    bool log = true;
    QString radioFreq;
    string playbookFile;
    bool noref = false;

    for (int i = 1; i < argc; ++i) {
        const char* var = argv[i];

        if (strcmp(var, "--help") == 0) {
            usage(argv[0]);
        } else if (strcmp(var, "-y") == 0) {
            blueTeam = false;
        } else if (strcmp(var, "-b") == 0) {
            blueTeam = true;
        } else if (strcmp(var, "-sim") == 0) {
            sim = true;
        } else if (strcmp(var, "-nolog") == 0) {
            log = false;
        } else if (strcmp(var, "-freq") == 0) {
            if (i + 1 >= argc) {
                printf("No radio frequency specified after -freq\n");
                usage(argv[0]);
            }

            i++;
            radioFreq = argv[i];
        } else if (strcmp(var, "-c") == 0) {
            if (i + 1 >= argc) {
                printf("no config file specified after -c\n");
                usage(argv[0]);
            }

            i++;
            cfgFile = argv[i];
        } else if (strcmp(var, "-s") == 0) {
            if (i + 1 >= argc) {
                printf("no seed specified after -s\n");
                usage(argv[0]);
            }

            i++;
            seed = strtol(argv[i], nullptr, 16);
        } else if (strcmp(var, "-pbk") == 0) {
            if (i + 1 >= argc) {
                printf("no playbook file specified after -pbk\n");
                usage(argv[0]);
            }

            playbookFile = argv[++i];
        } else if (strcmp(var, "-noref") == 0) {
            noref = true;
        } else {
            printf("Not a valid flag: %s\n", argv[i]);
            usage(argv[0]);
        }
    }

    printf("Running on %s\n", sim ? "simulation" : "real hardware\n");

    printf("seed %016lx\n", seed);
    srand48(seed);

    // Default config file name
    if (cfgFile.isNull()) {
        cfgFile = ApplicationRunDirectory().filePath(sim ? "soccer-sim.cfg"
                                                         : "soccer-real.cfg");
    }

    std::shared_ptr<Configuration> config =
        Configuration::FromRegisteredConfigurables();

    Processor* processor = new Processor(sim);
    processor->blueTeam(blueTeam);
    processor->refereeModule()->useExternalReferee(!noref);

    // Load config file
    QString error;
    if (!config->load(cfgFile, error)) {
        QMessageBox::critical(
            nullptr, "Soccer",
            QString("Can't read initial configuration %1:\n%2")
                .arg(cfgFile, error));
    }

    MainWindow* win = new MainWindow;
    win->configuration(config.get());
    win->processor(processor);

    win->setUseRefChecked(!noref);

    if (!QDir("logs").exists()) {
        fprintf(stderr, "No logs/ directory - not writing log file\n");
    } else if (!log) {
        fprintf(stderr, "Not writing log file\n");
    } else {
        QString logFile =
            QString("logs/") +
            QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss.log");
        if (!processor->openLog(logFile)) {
            printf("Failed to open %s: %m\n", (const char*)logFile.toLatin1());
        }
    }

    if (!radioFreq.isEmpty()) {
        if (radioFreq == "904")
            win->setRadioChannel(RadioChannels::MHz_904);
        else if (radioFreq == "906")
            win->setRadioChannel(RadioChannels::MHz_906);
        else
            printf("Cannot recognize radio frequency : %s\n",
                   radioFreq.toStdString().c_str());
    }

    win->logFileChanged();

    processor->start();

    if (playbookFile.size() > 0)
        processor->gameplayModule()->loadPlaybook(playbookFile);

    win->show();

    processor->gameplayModule()->setupUI();

    int ret = app.exec();
    processor->stop();

    delete win;
    delete processor;

    return ret;
}
<commit_msg>Revert "revertme: broke style compliance"<commit_after>
#include <gameplay/GameplayModule.hpp>

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <assert.h>
#include <signal.h>

#include <QApplication>
#include <QFile>
#include <QDir>
#include <QDateTime>
#include <QString>
#include <QMessageBox>

#include "MainWindow.hpp"
#include "Configuration.hpp"

using namespace std;

//  we use this to catch Ctrl+C and kill the program
void signal_handler(int signum) { exit(signum); }

void usage(const char* prog) {
    fprintf(stderr, "usage: %s [options...]\n", prog);
    fprintf(stderr, "\t-y:          run as the yellow team\n");
    fprintf(stderr, "\t-b:          run as the blue team\n");
    fprintf(stderr, "\t-c <file>:   specify the configuration file\n");
    fprintf(stderr, "\t-s <seed>:   set random seed (hexadecimal)\n");
    fprintf(stderr,
            "\t-pbk <file>: playbook file name as contained in "
            "'soccer/gameplay/playbooks/'\n");
    fprintf(stderr, "\t-ng:         no goalie\n");
    fprintf(stderr, "\t-sim:        use simulator\n");
    fprintf(stderr, "\t-freq:       specify radio frequency (906 or 904)\n");
    fprintf(stderr, "\t-nolog:      don't write log files\n");
    fprintf(stderr, "\t-noref:      don't use external referee commands\n");
    exit(1);
}

int main(int argc, char* argv[]) {
    printf("Starting Soccer...\n");

    //  register our signal handler
    signal(SIGINT, signal_handler);

    // Seed the large random number generator
    long int seed = 0;
    int fd = open("/dev/random", O_RDONLY);
    if (fd >= 0) {
        if (read(fd, &seed, sizeof(seed)) != sizeof(seed)) {
            fprintf(stderr, "Can't read /dev/random, using zero seed: %m\n");
        }
        close(fd);
    } else {
        fprintf(stderr, "Can't open /dev/random, using zero seed: %m\n");
    }

    QApplication app(argc, argv);

    bool blueTeam = false;
    QString cfgFile;
    vector<const char*> playDirs;
    bool sim = false;
    bool log = true;
    QString radioFreq;
    string playbookFile;
    bool noref = false;

    for (int i = 1; i < argc; ++i) {
        const char* var = argv[i];

        if (strcmp(var, "--help") == 0) {
            usage(argv[0]);
        } else if (strcmp(var, "-y") == 0) {
            blueTeam = false;
        } else if (strcmp(var, "-b") == 0) {
            blueTeam = true;
        } else if (strcmp(var, "-sim") == 0) {
            sim = true;
        } else if (strcmp(var, "-nolog") == 0) {
            log = false;
        } else if (strcmp(var, "-freq") == 0) {
            if (i + 1 >= argc) {
                printf("No radio frequency specified after -freq\n");
                usage(argv[0]);
            }

            i++;
            radioFreq = argv[i];
        } else if (strcmp(var, "-c") == 0) {
            if (i + 1 >= argc) {
                printf("no config file specified after -c\n");
                usage(argv[0]);
            }

            i++;
            cfgFile = argv[i];
        } else if (strcmp(var, "-s") == 0) {
            if (i + 1 >= argc) {
                printf("no seed specified after -s\n");
                usage(argv[0]);
            }

            i++;
            seed = strtol(argv[i], nullptr, 16);
        } else if (strcmp(var, "-pbk") == 0) {
            if (i + 1 >= argc) {
                printf("no playbook file specified after -pbk\n");
                usage(argv[0]);
            }

            playbookFile = argv[++i];
        } else if (strcmp(var, "-noref") == 0) {
            noref = true;
        } else {
            printf("Not a valid flag: %s\n", argv[i]);
            usage(argv[0]);
        }
    }

    printf("Running on %s\n", sim ? "simulation" : "real hardware\n");

    printf("seed %016lx\n", seed);
    srand48(seed);

    // Default config file name
    if (cfgFile.isNull()) {
        cfgFile = ApplicationRunDirectory().filePath(sim ? "soccer-sim.cfg"
                                                         : "soccer-real.cfg");
    }

    std::shared_ptr<Configuration> config =
        Configuration::FromRegisteredConfigurables();

    Processor* processor = new Processor(sim);
    processor->blueTeam(blueTeam);
    processor->refereeModule()->useExternalReferee(!noref);

    // Load config file
    QString error;
    if (!config->load(cfgFile, error)) {
        QMessageBox::critical(
            nullptr, "Soccer",
            QString("Can't read initial configuration %1:\n%2")
                .arg(cfgFile, error));
    }

    MainWindow* win = new MainWindow;
    win->configuration(config.get());
    win->processor(processor);

    win->setUseRefChecked(!noref);

    if (!QDir("logs").exists()) {
        fprintf(stderr, "No logs/ directory - not writing log file\n");
    } else if (!log) {
        fprintf(stderr, "Not writing log file\n");
    } else {
        QString logFile =
            QString("logs/") +
            QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss.log");
        if (!processor->openLog(logFile)) {
            printf("Failed to open %s: %m\n", (const char*)logFile.toLatin1());
        }
    }

    if (!radioFreq.isEmpty()) {
        if (radioFreq == "904")
            win->setRadioChannel(RadioChannels::MHz_904);
        else if (radioFreq == "906")
            win->setRadioChannel(RadioChannels::MHz_906);
        else
            printf("Cannot recognize radio frequency : %s\n",
                   radioFreq.toStdString().c_str());
    }

    win->logFileChanged();

    processor->start();

    if (playbookFile.size() > 0)
        processor->gameplayModule()->loadPlaybook(playbookFile);

    win->show();

    processor->gameplayModule()->setupUI();

    int ret = app.exec();
    processor->stop();

    delete win;
    delete processor;

    return ret;
}
<|endoftext|>


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

//-----------------------------------------------------------------
//         AliAnalysisTaskSpectraAllChAOD class
//-----------------------------------------------------------------

#include "TChain.h"
#include "TTree.h"
#include "TLegend.h"
#include "TH1F.h"
#include "TH2F.h"
#include "THnSparse.h"
#include "TCanvas.h"
#include "AliAnalysisTask.h"
#include "AliAODTrack.h"
#include "AliAODMCParticle.h"
#include "AliVParticle.h"
#include "AliAODEvent.h"
#include "AliAODInputHandler.h"
#include "AliAnalysisTaskSpectraAllChAOD.h"
#include "AliAnalysisTaskESDfilter.h"
#include "AliAnalysisDataContainer.h"
#include "AliSpectraAODTrackCuts.h"
#include "AliSpectraAODEventCuts.h"
#include "AliCentrality.h"
#include "TProof.h"
#include "AliVEvent.h"
#include "AliStack.h"
#include <TMCProcess.h>

#include <iostream>

using namespace std;

ClassImp(AliAnalysisTaskSpectraAllChAOD)

//________________________________________________________________________
AliAnalysisTaskSpectraAllChAOD::AliAnalysisTaskSpectraAllChAOD(const char *name) : AliAnalysisTaskSE(name), fAOD(0), fTrackCuts(0), fEventCuts(0), fIsMC(0), fOutput(0)
{
  // Default constructor

  DefineInput(0, TChain::Class());
  DefineOutput(1, TList::Class());
  DefineOutput(2, AliSpectraAODEventCuts::Class());
  DefineOutput(3, AliSpectraAODTrackCuts::Class());

}
//________________________________________________________________________
//________________________________________________________________________
void AliAnalysisTaskSpectraAllChAOD::UserCreateOutputObjects()
{
  // create output objects
  fOutput=new TList();
  fOutput->SetOwner();
  fOutput->SetName("fOutput");

  if (!fTrackCuts) AliFatal("Track Cuts should be set in the steering macro");
  if (!fEventCuts) AliFatal("Event Cuts should be set in the steering macro");

  //dimensions of standard THnSparse
  const Int_t nvar=4;
  const Double_t ptBins[] = {0.05,0.1,0.12,0.14,0.16,0.18,0.20,0.25,0.30,0.35,0.4,0.45,0.5,0.55,0.6,0.65,0.7,0.75,0.8,0.85,0.9,0.95,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,2.9,3.0,3.2,3.4,3.6,3.8,4.0,4.2,4.4,4.6,4.8,5.0};
  Int_t nptBins=52;

  Int_t    binsHistReal[nvar] = {   100,   100,      nptBins,     20};
  Double_t xminHistReal[nvar] = {    0.,     0,            0.,      0.};
  Double_t xmaxHistReal[nvar] = {  10.,   10.,            5.,   100.};

  THnSparseF* NSparseHist = new THnSparseF("NSparseHist","NSparseHist",nvar,binsHistReal,xminHistReal,xmaxHistReal);
  NSparseHist->GetAxis(0)->SetTitle("Q vec VZERO-C");
  NSparseHist->GetAxis(1)->SetTitle("Q vec VZERO-A");
  NSparseHist->GetAxis(2)->SetTitle("#it{p}_{T}");
  NSparseHist->SetBinEdges(2,ptBins);
  NSparseHist->GetAxis(3)->SetTitle(Form("%s cent",fEventCuts->GetCentralityMethod().Data()));
  fOutput->Add(NSparseHist);

  TH2F* hGen = new TH2F("hGen","hGen",nptBins,ptBins,20,0.,100.);
  hGen->GetXaxis()->SetTitle("#it{p}_{T,Gen}");
  hGen->GetYaxis()->SetTitle(Form("%s cent",fEventCuts->GetCentralityMethod().Data()));
  fOutput->Add(hGen);

  TH2F* hRec = new TH2F("hRec","hRec",nptBins,ptBins,20,0.,100.);
  hRec->GetXaxis()->SetTitle("#it{p}_{T,Rec}");
  hRec->GetYaxis()->SetTitle(Form("%s cent",fEventCuts->GetCentralityMethod().Data()));
  fOutput->Add(hRec);

  PostData(1, fOutput  );
  PostData(2, fEventCuts);
  PostData(3, fTrackCuts);

}
//________________________________________________________________________
void AliAnalysisTaskSpectraAllChAOD::UserExec(Option_t *)
{
  // main event loop
  fAOD = dynamic_cast<AliAODEvent*>(fInputEvent);
  if (!fAOD) {
    AliWarning("ERROR: AliAODEvent not available \n");
    return;
  }

  if (strcmp(fAOD->ClassName(), "AliAODEvent"))
    {
      AliFatal("Not processing AODs");
    }

  if(!fEventCuts->IsSelected(fAOD,fTrackCuts))return;//event selection

  // First do MC to fill up the MC particle array, such that we can use it later
  TClonesArray *arrayMC = 0;
  if (fIsMC)
    {
      arrayMC = (TClonesArray*) fAOD->GetList()->FindObject(AliAODMCParticle::StdBranchName());
      if (!arrayMC) {
	AliFatal("Error: MC particles branch not found!\n");
      }
      Int_t nMC = arrayMC->GetEntries();
      for (Int_t iMC = 0; iMC < nMC; iMC++)
	{
	  AliAODMCParticle *partMC = (AliAODMCParticle*) arrayMC->At(iMC);
	  if(!partMC->Charge()) continue;//Skip neutrals
	  if(!partMC->IsPhysicalPrimary()) continue; //skip secondaries
	  if(partMC->Eta() < fTrackCuts->GetEtaMin() || partMC->Eta() > fTrackCuts->GetEtaMax())continue;//ETA CUT ON GENERATED!!!!!!!!!!!!!!!!!!!!!!!!!!

	  ((TH2F*)fOutput->FindObject("hGen"))->Fill(partMC->Pt(),fEventCuts->GetCent());
	  //Printf("a particle");

	}
    }

  //main loop on tracks
  for (Int_t iTracks = 0; iTracks < fAOD->GetNumberOfTracks(); iTracks++) {
    AliAODTrack* track = fAOD->GetTrack(iTracks);
    if (!fTrackCuts->IsSelected(track,kTRUE)) continue;

    ((TH2F*)fOutput->FindObject("hRec"))->Fill(track->Pt(),fEventCuts->GetCent());

    Double_t var[4];
    var[0]=fEventCuts->GetqV0C();
    var[1]=fEventCuts->GetqV0A();
    var[2]=track->Pt();
    var[3]=fEventCuts->GetCent();
    ((THnSparseF*)fOutput->FindObject("NSparseHist"))->Fill(var);

    //Printf("a track");

  } // end loop on tracks

  PostData(1, fOutput  );
  PostData(2, fEventCuts);
  PostData(3, fTrackCuts);
}

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

//-----------------------------------------------------------------
//         AliAnalysisTaskSpectraAllChAOD class
//-----------------------------------------------------------------

#include "TChain.h"
#include "TTree.h"
#include "TLegend.h"
#include "TH1F.h"
#include "TH2F.h"
#include "THnSparse.h"
#include "TCanvas.h"
#include "AliAnalysisTask.h"
#include "AliAODTrack.h"
#include "AliAODMCParticle.h"
#include "AliVParticle.h"
#include "AliAODEvent.h"
#include "AliAODInputHandler.h"
#include "AliAnalysisTaskSpectraAllChAOD.h"
#include "AliAnalysisTaskESDfilter.h"
#include "AliAnalysisDataContainer.h"
#include "AliSpectraAODTrackCuts.h"
#include "AliSpectraAODEventCuts.h"
#include "AliCentrality.h"
#include "TProof.h"
#include "AliVEvent.h"
#include "AliStack.h"
#include <TMCProcess.h>

#include <iostream>

using namespace std;

ClassImp(AliAnalysisTaskSpectraAllChAOD)

//________________________________________________________________________
AliAnalysisTaskSpectraAllChAOD::AliAnalysisTaskSpectraAllChAOD(const char *name) : AliAnalysisTaskSE(name), fAOD(0), fTrackCuts(0), fEventCuts(0), fIsMC(0), fOutput(0)
{
  // Default constructor

  DefineInput(0, TChain::Class());
  DefineOutput(1, TList::Class());
  DefineOutput(2, AliSpectraAODEventCuts::Class());
  DefineOutput(3, AliSpectraAODTrackCuts::Class());

}
//________________________________________________________________________
//________________________________________________________________________
void AliAnalysisTaskSpectraAllChAOD::UserCreateOutputObjects()
{
  // create output objects
  fOutput=new TList();
  fOutput->SetOwner();
  fOutput->SetName("fOutput");

  if (!fTrackCuts) AliFatal("Track Cuts should be set in the steering macro");
  if (!fEventCuts) AliFatal("Event Cuts should be set in the steering macro");

  //dimensions of standard THnSparse
  const Int_t nvar=4;
  const Double_t ptBins[] = {0.05,0.1,0.12,0.14,0.16,0.18,0.20,0.25,0.30,0.35,0.4,0.45,0.5,0.55,0.6,0.65,0.7,0.75,0.8,0.85,0.9,0.95,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,2.9,3.0,3.2,3.4,3.6,3.8,4.0,4.2,4.4,4.6,4.8,5.0,5.5,6.0,6.5,7.0,7.5,8.0,8.5,9.0,9.5,10.,11.,12.,13.,14.,15.};
  Int_t nptBins=67;

  Int_t    binsHistReal[nvar] = {   100,   100,      nptBins,     20};
  Double_t xminHistReal[nvar] = {    0.,     0,            0.,      0.};
  Double_t xmaxHistReal[nvar] = {  10.,   10.,            5.,   100.};

  THnSparseF* NSparseHist = new THnSparseF("NSparseHist","NSparseHist",nvar,binsHistReal,xminHistReal,xmaxHistReal);
  NSparseHist->GetAxis(0)->SetTitle("Q vec VZERO-C");
  NSparseHist->GetAxis(1)->SetTitle("Q vec VZERO-A");
  NSparseHist->GetAxis(2)->SetTitle("#it{p}_{T}");
  NSparseHist->SetBinEdges(2,ptBins);
  NSparseHist->GetAxis(3)->SetTitle(Form("%s cent",fEventCuts->GetCentralityMethod().Data()));
  fOutput->Add(NSparseHist);

  TH2F* hGen = new TH2F("hGen","hGen",nptBins,ptBins,20,0.,100.);
  hGen->GetXaxis()->SetTitle("#it{p}_{T,Gen}");
  hGen->GetYaxis()->SetTitle(Form("%s cent",fEventCuts->GetCentralityMethod().Data()));
  fOutput->Add(hGen);

  TH2F* hRec = new TH2F("hRec","hRec",nptBins,ptBins,20,0.,100.);
  hRec->GetXaxis()->SetTitle("#it{p}_{T,Rec}");
  hRec->GetYaxis()->SetTitle(Form("%s cent",fEventCuts->GetCentralityMethod().Data()));
  fOutput->Add(hRec);

  PostData(1, fOutput  );
  PostData(2, fEventCuts);
  PostData(3, fTrackCuts);

}
//________________________________________________________________________
void AliAnalysisTaskSpectraAllChAOD::UserExec(Option_t *)
{
  // main event loop
  fAOD = dynamic_cast<AliAODEvent*>(fInputEvent);
  if (!fAOD) {
    AliWarning("ERROR: AliAODEvent not available \n");
    return;
  }

  if (strcmp(fAOD->ClassName(), "AliAODEvent"))
    {
      AliFatal("Not processing AODs");
    }

  if(!fEventCuts->IsSelected(fAOD,fTrackCuts))return;//event selection

  // First do MC to fill up the MC particle array, such that we can use it later
  TClonesArray *arrayMC = 0;
  if (fIsMC)
    {
      arrayMC = (TClonesArray*) fAOD->GetList()->FindObject(AliAODMCParticle::StdBranchName());
      if (!arrayMC) {
	AliFatal("Error: MC particles branch not found!\n");
      }
      Int_t nMC = arrayMC->GetEntries();
      for (Int_t iMC = 0; iMC < nMC; iMC++)
	{
	  AliAODMCParticle *partMC = (AliAODMCParticle*) arrayMC->At(iMC);
	  if(!partMC->Charge()) continue;//Skip neutrals
	  if(!partMC->IsPhysicalPrimary()) continue; //skip secondaries
	  if(partMC->Eta() < fTrackCuts->GetEtaMin() || partMC->Eta() > fTrackCuts->GetEtaMax())continue;//ETA CUT ON GENERATED!!!!!!!!!!!!!!!!!!!!!!!!!!

	  ((TH2F*)fOutput->FindObject("hGen"))->Fill(partMC->Pt(),fEventCuts->GetCent());
	  //Printf("a particle");

	}
    }

  //main loop on tracks
  for (Int_t iTracks = 0; iTracks < fAOD->GetNumberOfTracks(); iTracks++) {
    AliAODTrack* track = fAOD->GetTrack(iTracks);
    if (!fTrackCuts->IsSelected(track,kTRUE)) continue;

    ((TH2F*)fOutput->FindObject("hRec"))->Fill(track->Pt(),fEventCuts->GetCent());

    Double_t var[4];
    var[0]=fEventCuts->GetqV0C();
    var[1]=fEventCuts->GetqV0A();
    var[2]=track->Pt();
    var[3]=fEventCuts->GetCent();
    ((THnSparseF*)fOutput->FindObject("NSparseHist"))->Fill(var);

    //Printf("a track");

  } // end loop on tracks

  PostData(1, fOutput  );
  PostData(2, fEventCuts);
  PostData(3, fTrackCuts);
}

//_________________________________________________________________
void   AliAnalysisTaskSpectraAllChAOD::Terminate(Option_t *)
{
  // Terminate
}
<|endoftext|>


<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double fSigcheckVerificationFactor = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64 nTimeLastCheckpoint;
        int64 nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        (  1500, uint256("0x841a2965955dd288cfa707a755d05a54e45f8bd476835ec9af4402a2b59a2967"))
        (  4032, uint256("0x9ce90e427198fc0ef05e5905ce3503725b80e26afd35a987965fd7e3d9cf0846"))
        (  8064, uint256("0xeb984353fc5190f210651f150c40b8a4bab9eeeff0b729fcb3987da694430d70"))
        ( 16128, uint256("0x602edf1859b7f9a6af809f1d9b0e6cb66fdc1d4d9dcd7a4bec03e12a1ccd153d"))
        ( 23420, uint256("0xd80fdf9ca81afd0bd2b2a90ac3a9fe547da58f2530ec874e978fce0b5101b507"))
        ( 50000, uint256("0x69dc37eb029b68f075a5012dcc0419c127672adb4f3a32882b2b3e71d07a20a6"))
        ( 80000, uint256("0x4fcb7c02f676a300503f49c764a89955a8f920b46a8cbecb4867182ecdb2e90a"))
        (120000, uint256("0xbd9d26924f05f6daa7f0155f32828ec89e8e29cee9e7121b026a7a3552ac6131"))
        (161500, uint256("0xdbe89880474f4bb4f75c227c77ba1cdc024991123b28b8418dbbf7798471ff43"))
        (179620, uint256("0x2ad9c65c990ac00426d18e446e0fd7be2ffa69e9a7dcb28358a50b2b78b9f709"))
        (240000, uint256("0x7140d1c4b4c2157ca217ee7636f24c9c73db39c4590c4e6eab2e3ea1555088aa"))
        (383640, uint256("0x2b6809f094a9215bafc65eb3f110a35127a34be94b7d0590a096c3f126c6f364"))
        (409004, uint256("0x487518d663d9f1fa08611d9395ad74d982b667fbdc0e77e9cf39b4f1355908a3"))
        (456000, uint256("0xbf34f71cc6366cd487930d06be22f897e34ca6a40501ac7d401be32456372004"))
        (541794, uint256("0x1cbccbe6920e7c258bbce1f26211084efb19764aa3224bec3f4320d77d6a2fd2"))
        (585010, uint256("0xea9ea06840de20a18a66acb07c9102ee6374ad2cbafc71794e576354fea5df2d"))
        (638902, uint256("0x15238656e8ec63d28de29a8c75fcf3a5819afc953dcd9cc45cecc53baec74f38"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1410516073, // * UNIX timestamp of last checkpoint block
        4896865,    // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        7000.0     // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        (   546, uint256("0xa0fea99a6897f531600c8ae53367b126824fd6a847b2b2b73817a95b8e27e602"))
        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        1365458829,
        547,
        576
    };

    const CCheckpointData &Checkpoints() {
        if (fTestNet)
            return dataTestnet;
        else
            return data;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (!GetBoolArg("-checkpoints", true))
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex) {
        if (pindex==NULL)
            return 0.0;

        int64 nNow = time(NULL);

        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (!GetBoolArg("-checkpoints", true))
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (!GetBoolArg("-checkpoints", true))
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }
}
<commit_msg>remove checkpoints<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double fSigcheckVerificationFactor = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64 nTimeLastCheckpoint;
        int64 nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        (0, uint256("0x"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        //1410516073, // * UNIX timestamp of last checkpoint block
        //4896865,    // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        //7000.0     // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        (   0, uint256("0x"))
        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        //1365458829,
        //547,
        //576
    };

    const CCheckpointData &Checkpoints() {
        if (fTestNet)
            return dataTestnet;
        else
            return data;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (!GetBoolArg("-checkpoints", true))
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex) {
        if (pindex==NULL)
            return 0.0;

        int64 nNow = time(NULL);

        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (!GetBoolArg("-checkpoints", true))
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (!GetBoolArg("-checkpoints", true))
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }
}
<|endoftext|>


<commit_before>/*
 Copyright (c) 2017, Ford Motor Company
 All rights reserved.

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

 Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.

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

 Neither the name of the Ford Motor Company nor the names of its contributors
 may be used to endorse or promote products derived from this software
 without specific prior written permission.

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

#include "remote_control/remote_control_plugin.h"
#include "remote_control/rc_command_factory.h"
#include "remote_control/remote_control_event.h"
#include "remote_control/rc_module_constants.h"
#include "remote_control/rc_app_extension.h"
#include "remote_control/message_helper.h"
#include "utils/logger.h"
#include "interfaces/MOBILE_API.h"
#include "utils/macro.h"
#include "utils/make_shared.h"
#include "application_manager/smart_object_keys.h"

namespace remote_control {

using functional_modules::ProcessResult;
using functional_modules::GenericModule;
using functional_modules::PluginInfo;
using functional_modules::RCFunctionID;
namespace hmi_api = functional_modules::hmi_api;

using namespace json_keys;

CREATE_LOGGERPTR_GLOBAL(logger_, "RemoteControl");

EXPORT_FUNCTION_IMPL(remote_control::RemoteControlPlugin);

RemoteControlPlugin::RemoteControlPlugin()
    : is_scan_started_(false), resource_allocation_manager_(*this) {
  plugin_info_.name = "RemoteControlPlugin";
  plugin_info_.version = 1;
  SubscribeOnFunctions();
}

void RemoteControlPlugin::SubscribeOnFunctions() {
  plugin_info_.rc_function_list.push_back(RCFunctionID::BUTTON_PRESS);
  plugin_info_.rc_function_list.push_back(
      RCFunctionID::GET_INTERIOR_VEHICLE_DATA);
  plugin_info_.rc_function_list.push_back(
      RCFunctionID::SET_INTERIOR_VEHICLE_DATA);
  plugin_info_.rc_function_list.push_back(
      RCFunctionID::ON_INTERIOR_VEHICLE_DATA);

  plugin_info_.hmi_function_list.push_back(hmi_api::get_interior_vehicle_data);
  plugin_info_.hmi_function_list.push_back(hmi_api::set_interior_vehicle_data);
  plugin_info_.hmi_function_list.push_back(hmi_api::on_interior_vehicle_data);
  plugin_info_.hmi_function_list.push_back(hmi_api::button_press);
  plugin_info_.hmi_function_list.push_back(hmi_api::get_user_consent);
  plugin_info_.hmi_function_list.push_back(hmi_api::on_remote_control_settings);
}

RemoteControlPlugin::~RemoteControlPlugin() {
  RemoveAppExtensions();
}

functional_modules::PluginInfo RemoteControlPlugin::GetPluginInfo() const {
  return plugin_info_;
}

const std::string ExtractFunctionAndAddMetadata(
    const Json::Value& value, application_manager::Message& out_msg) {
  if (value.isMember(json_keys::kMethod)) {
    const std::string& function_name =
        value.get(json_keys::kMethod, "").asCString();

    // Existence of method name must be guaranteed by plugin manager
    DCHECK_OR_RETURN(!function_name.empty(), "");

    if (value.isMember(json_keys::kId)) {
      out_msg.set_correlation_id(value.get(json_keys::kId, "").asInt());
      out_msg.set_message_type(application_manager::MessageType::kRequest);
    } else {
      out_msg.set_message_type(application_manager::MessageType::kNotification);
    }
    return function_name;
  }

  if (value.isMember(json_keys::kResult)) {
    const Json::Value& result = value.get(json_keys::kResult, Json::Value());
    const std::string& function_name =
        result.get(json_keys::kMethod, "").asCString();
    out_msg.set_correlation_id(value.get(json_keys::kId, "").asInt());

    // Existence of method name must be guaranteed by plugin manager
    DCHECK_OR_RETURN(!function_name.empty(), "");

    out_msg.set_message_type(application_manager::MessageType::kResponse);
    return function_name;
  }

  if (value.isMember(json_keys::kError)) {
    const Json::Value& error = value.get(json_keys::kError, Json::Value());
    const Json::Value& data = error.get(json_keys::kData, Json::Value());
    const std::string& function_name =
        data.get(json_keys::kMethod, "").asCString();

    // Existence of method name must be guaranteed by plugin manager
    DCHECK_OR_RETURN(!function_name.empty(), "");

    out_msg.set_message_type(application_manager::MessageType::kErrorResponse);
    out_msg.set_correlation_id(value.get(json_keys::kId, "").asInt());
    return function_name;
  }
  return std::string();
}

ProcessResult RemoteControlPlugin::ProcessMessage(
    application_manager::MessagePtr msg) {
  DCHECK_OR_RETURN(msg, ProcessResult::FAILED);

  const std::string& function_name = MessageHelper::GetMobileAPIName(
      static_cast<functional_modules::RCFunctionID>(msg->function_id()));

  LOG4CXX_DEBUG(logger_, "Function name to set : " << function_name);
  msg->set_function_name(function_name);

  LOG4CXX_DEBUG(logger_, "Mobile message: " << msg->json_message());

  request_controller::MobileRequestPtr command(
      RCCommandFactory::CreateCommand(msg, *this));
  if (command) {
    request_controller_.AddRequest(msg->correlation_id(), command);
    command->Run();
  } else {
    return ProcessResult::CANNOT_PROCESS;
  }

  return ProcessResult::PROCESSED;
}

ProcessResult RemoteControlPlugin::ProcessHMIMessage(
    application_manager::MessagePtr msg) {
  LOG4CXX_AUTO_TRACE(logger_);

  Json::Value value;
  Json::Reader reader;
  reader.parse(msg->json_message(), value);
  LOG4CXX_TRACE(logger_, "Process " << msg->json_message());
  const std::string& function_name = ExtractFunctionAndAddMetadata(value, *msg);

  // Existence of method name must be guaranteed by plugin manager
  DCHECK_OR_RETURN(!function_name.empty(), ProcessResult::FAILED);

  LOG4CXX_DEBUG(logger_, "Process " << function_name);

  switch (msg->type()) {
    case application_manager::MessageType::kResponse:
    case application_manager::MessageType::kErrorResponse: {
      RCPluginEvent event(msg, function_name);
      LOG4CXX_DEBUG(logger_, "Response received");
      event_dispatcher_.raise_event(event);
      return ProcessResult::PROCESSED;
    }
    case application_manager::MessageType::kRequest:
    case application_manager::MessageType::kNotification: {
      if (hmi_api::on_interior_vehicle_data == function_name) {
        msg->set_function_id(functional_modules::ON_INTERIOR_VEHICLE_DATA);
      }
      if (hmi_api::on_remote_control_settings == function_name) {
        msg->set_function_id(functional_modules::ON_REMOTE_CONTROL_SETTINGS);
      }
      const application_manager::MessageValidationResult validation_result =
          service()->ValidateMessageBySchema(*msg);
      utils::SharedPtr<commands::Command> command =
          RCCommandFactory::CreateCommand(msg, *this);
      if ((validation_result ==
           application_manager::MessageValidationResult::SUCCESS) &&
          command) {
        command->Run();
        return ProcessResult::PROCESSED;
      }
      LOG4CXX_DEBUG(logger_, "Message validation failed");
      break;
    }
    default: { LOG4CXX_DEBUG(logger_, "Unknown message type"); }
  }
  return ProcessResult::CANNOT_PROCESS;
}

void RemoteControlPlugin::SendHmiStatusNotification(
    application_manager::ApplicationSharedPtr app) {
  LOG4CXX_AUTO_TRACE(logger_);
  application_manager::MessagePtr msg = new application_manager::Message(
      protocol_handler::MessagePriority::kDefault);
  Json::Value msg_params;

  msg->set_function_id(mobile_apis::FunctionID::OnHMIStatusID);
  msg->set_message_type(application_manager::MessageType::kNotification);

  msg->set_connection_key(app->app_id());
  msg->set_protocol_version(app->protocol_version());

  msg_params["hmiLevel"] = static_cast<uint32_t>(app->hmi_level());

  msg_params["audioStreamingState"] =
      static_cast<uint32_t>(app->audio_streaming_state());

  msg_params["systemContext"] = static_cast<uint32_t>(app->system_context());

  msg->set_json_message(MessageHelper::ValueToString(msg_params));

  service()->SendMessageToMobile(msg);
}

void RemoteControlPlugin::SendResponseToMobile(
    application_manager::MessagePtr msg) {
  LOG4CXX_DEBUG(logger_, "Response to mobile: " << msg->json_message());
  service()->SendMessageToMobile(msg);
  request_controller_.DeleteRequest(msg->correlation_id());
}

void RemoteControlPlugin::SendTimeoutResponseToMobile(
    application_manager::MessagePtr msg) {
  LOG4CXX_DEBUG(
      logger_,
      "Timeout is expired. Response to mobile: " << msg->json_message());
  service()->SendMessageToMobile(msg);
}

void RemoteControlPlugin::RemoveAppExtensions() {
  std::vector<application_manager::ApplicationSharedPtr> applications =
      service()->GetApplications(GetModuleID());

  std::vector<application_manager::ApplicationSharedPtr>::iterator it =
      applications.begin();

  for (; it != applications.end(); ++it) {
    application_manager::ApplicationSharedPtr app = *it;
    if (app) {
      app->RemoveExtension(GetModuleID());
    }
  }
}

void RemoteControlPlugin::RemoveAppExtension(uint32_t app_id) {
  application_manager::ApplicationSharedPtr app =
      service()->GetApplication(app_id);

  if (app) {
    app->RemoveExtension(GetModuleID());
  }
}

bool RemoteControlPlugin::IsAppForPlugin(
    application_manager::ApplicationSharedPtr app) {
  LOG4CXX_AUTO_TRACE(logger_);
  application_manager::AppExtensionPtr app_extension =
      app->QueryInterface(GetModuleID());
  if (app_extension) {
    return true;
  }

  if (service()->IsRemoteControlApplication(app)) {
    RCAppExtensionPtr rc_app_extension = new RCAppExtension(GetModuleID());
    app->AddExtension(rc_app_extension);
    service()->NotifyHMIAboutHMILevel(app, app->hmi_level());
    return true;
  }
  return false;
}

void RemoteControlPlugin::OnAppHMILevelChanged(
    application_manager::ApplicationSharedPtr app,
    mobile_apis::HMILevel::eType) {
  LOG4CXX_DEBUG(logger_,
                "RSDL application " << app->name().AsMBString()
                                    << " has changed hmi level to "
                                    << app->hmi_level());
  service()->NotifyHMIAboutHMILevel(app, app->hmi_level());
}

void RemoteControlPlugin::OnPluginServiceChanged() {
  LOG4CXX_AUTO_TRACE(logger_);
  const functional_modules::TimeUnit timeout_msec =
      service()->GetSettings().default_timeout();
  request_controller_.SetRequestTimeout(timeout_msec / 1000);
}

void RemoteControlPlugin::set_service(application_manager::ServicePtr service) {
  RemotePluginInterface::set_service(service);
  OnPluginServiceChanged();
}

RCEventDispatcher& RemoteControlPlugin::event_dispatcher() {
  return event_dispatcher_;
}

ResourceAllocationManager& RemoteControlPlugin::resource_allocation_manager() {
  return resource_allocation_manager_;
}

void RemoteControlPlugin::OnApplicationEvent(
    functional_modules::ApplicationEvent event,
    application_manager::ApplicationSharedPtr application) {
  LOG4CXX_AUTO_TRACE(logger_);
  if (false == service()->IsRemoteControlApplication(application)) {
    LOG4CXX_DEBUG(logger_,
                  "Application " << application->app_id()
                                 << " has no remote control functionality."
                                 << " Event will be ignored for RC plugin");
    return;
  }
  resource_allocation_manager_.OnApplicationEvent(event, application);
}

void RemoteControlPlugin::OnPolicyEvent(functional_modules::PolicyEvent event) {
  LOG4CXX_AUTO_TRACE(logger_);
  resource_allocation_manager_.OnPolicyEvent(event);
}

}  //  namespace remote_control
<commit_msg>Activate app sent at wrong time for RC apps<commit_after>/*
 Copyright (c) 2017, Ford Motor Company
 All rights reserved.

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

 Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.

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

 Neither the name of the Ford Motor Company nor the names of its contributors
 may be used to endorse or promote products derived from this software
 without specific prior written permission.

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

#include "remote_control/remote_control_plugin.h"
#include "remote_control/rc_command_factory.h"
#include "remote_control/remote_control_event.h"
#include "remote_control/rc_module_constants.h"
#include "remote_control/rc_app_extension.h"
#include "remote_control/message_helper.h"
#include "utils/logger.h"
#include "interfaces/MOBILE_API.h"
#include "utils/macro.h"
#include "utils/make_shared.h"
#include "application_manager/smart_object_keys.h"

namespace remote_control {

using functional_modules::ProcessResult;
using functional_modules::GenericModule;
using functional_modules::PluginInfo;
using functional_modules::RCFunctionID;
namespace hmi_api = functional_modules::hmi_api;

using namespace json_keys;

CREATE_LOGGERPTR_GLOBAL(logger_, "RemoteControl");

EXPORT_FUNCTION_IMPL(remote_control::RemoteControlPlugin);

RemoteControlPlugin::RemoteControlPlugin()
    : is_scan_started_(false), resource_allocation_manager_(*this) {
  plugin_info_.name = "RemoteControlPlugin";
  plugin_info_.version = 1;
  SubscribeOnFunctions();
}

void RemoteControlPlugin::SubscribeOnFunctions() {
  plugin_info_.rc_function_list.push_back(RCFunctionID::BUTTON_PRESS);
  plugin_info_.rc_function_list.push_back(
      RCFunctionID::GET_INTERIOR_VEHICLE_DATA);
  plugin_info_.rc_function_list.push_back(
      RCFunctionID::SET_INTERIOR_VEHICLE_DATA);
  plugin_info_.rc_function_list.push_back(
      RCFunctionID::ON_INTERIOR_VEHICLE_DATA);

  plugin_info_.hmi_function_list.push_back(hmi_api::get_interior_vehicle_data);
  plugin_info_.hmi_function_list.push_back(hmi_api::set_interior_vehicle_data);
  plugin_info_.hmi_function_list.push_back(hmi_api::on_interior_vehicle_data);
  plugin_info_.hmi_function_list.push_back(hmi_api::button_press);
  plugin_info_.hmi_function_list.push_back(hmi_api::get_user_consent);
  plugin_info_.hmi_function_list.push_back(hmi_api::on_remote_control_settings);
}

RemoteControlPlugin::~RemoteControlPlugin() {
  RemoveAppExtensions();
}

functional_modules::PluginInfo RemoteControlPlugin::GetPluginInfo() const {
  return plugin_info_;
}

const std::string ExtractFunctionAndAddMetadata(
    const Json::Value& value, application_manager::Message& out_msg) {
  if (value.isMember(json_keys::kMethod)) {
    const std::string& function_name =
        value.get(json_keys::kMethod, "").asCString();

    // Existence of method name must be guaranteed by plugin manager
    DCHECK_OR_RETURN(!function_name.empty(), "");

    if (value.isMember(json_keys::kId)) {
      out_msg.set_correlation_id(value.get(json_keys::kId, "").asInt());
      out_msg.set_message_type(application_manager::MessageType::kRequest);
    } else {
      out_msg.set_message_type(application_manager::MessageType::kNotification);
    }
    return function_name;
  }

  if (value.isMember(json_keys::kResult)) {
    const Json::Value& result = value.get(json_keys::kResult, Json::Value());
    const std::string& function_name =
        result.get(json_keys::kMethod, "").asCString();
    out_msg.set_correlation_id(value.get(json_keys::kId, "").asInt());

    // Existence of method name must be guaranteed by plugin manager
    DCHECK_OR_RETURN(!function_name.empty(), "");

    out_msg.set_message_type(application_manager::MessageType::kResponse);
    return function_name;
  }

  if (value.isMember(json_keys::kError)) {
    const Json::Value& error = value.get(json_keys::kError, Json::Value());
    const Json::Value& data = error.get(json_keys::kData, Json::Value());
    const std::string& function_name =
        data.get(json_keys::kMethod, "").asCString();

    // Existence of method name must be guaranteed by plugin manager
    DCHECK_OR_RETURN(!function_name.empty(), "");

    out_msg.set_message_type(application_manager::MessageType::kErrorResponse);
    out_msg.set_correlation_id(value.get(json_keys::kId, "").asInt());
    return function_name;
  }
  return std::string();
}

ProcessResult RemoteControlPlugin::ProcessMessage(
    application_manager::MessagePtr msg) {
  DCHECK_OR_RETURN(msg, ProcessResult::FAILED);

  const std::string& function_name = MessageHelper::GetMobileAPIName(
      static_cast<functional_modules::RCFunctionID>(msg->function_id()));

  LOG4CXX_DEBUG(logger_, "Function name to set : " << function_name);
  msg->set_function_name(function_name);

  LOG4CXX_DEBUG(logger_, "Mobile message: " << msg->json_message());

  request_controller::MobileRequestPtr command(
      RCCommandFactory::CreateCommand(msg, *this));
  if (command) {
    request_controller_.AddRequest(msg->correlation_id(), command);
    command->Run();
  } else {
    return ProcessResult::CANNOT_PROCESS;
  }

  return ProcessResult::PROCESSED;
}

ProcessResult RemoteControlPlugin::ProcessHMIMessage(
    application_manager::MessagePtr msg) {
  LOG4CXX_AUTO_TRACE(logger_);

  Json::Value value;
  Json::Reader reader;
  reader.parse(msg->json_message(), value);
  LOG4CXX_TRACE(logger_, "Process " << msg->json_message());
  const std::string& function_name = ExtractFunctionAndAddMetadata(value, *msg);

  // Existence of method name must be guaranteed by plugin manager
  DCHECK_OR_RETURN(!function_name.empty(), ProcessResult::FAILED);

  LOG4CXX_DEBUG(logger_, "Process " << function_name);

  switch (msg->type()) {
    case application_manager::MessageType::kResponse:
    case application_manager::MessageType::kErrorResponse: {
      RCPluginEvent event(msg, function_name);
      LOG4CXX_DEBUG(logger_, "Response received");
      event_dispatcher_.raise_event(event);
      return ProcessResult::PROCESSED;
    }
    case application_manager::MessageType::kRequest:
    case application_manager::MessageType::kNotification: {
      if (hmi_api::on_interior_vehicle_data == function_name) {
        msg->set_function_id(functional_modules::ON_INTERIOR_VEHICLE_DATA);
      }
      if (hmi_api::on_remote_control_settings == function_name) {
        msg->set_function_id(functional_modules::ON_REMOTE_CONTROL_SETTINGS);
      }
      const application_manager::MessageValidationResult validation_result =
          service()->ValidateMessageBySchema(*msg);
      utils::SharedPtr<commands::Command> command =
          RCCommandFactory::CreateCommand(msg, *this);
      if ((validation_result ==
           application_manager::MessageValidationResult::SUCCESS) &&
          command) {
        command->Run();
        return ProcessResult::PROCESSED;
      }
      LOG4CXX_DEBUG(logger_, "Message validation failed");
      break;
    }
    default: { LOG4CXX_DEBUG(logger_, "Unknown message type"); }
  }
  return ProcessResult::CANNOT_PROCESS;
}

void RemoteControlPlugin::SendHmiStatusNotification(
    application_manager::ApplicationSharedPtr app) {
  LOG4CXX_AUTO_TRACE(logger_);
  application_manager::MessagePtr msg = new application_manager::Message(
      protocol_handler::MessagePriority::kDefault);
  Json::Value msg_params;

  msg->set_function_id(mobile_apis::FunctionID::OnHMIStatusID);
  msg->set_message_type(application_manager::MessageType::kNotification);

  msg->set_connection_key(app->app_id());
  msg->set_protocol_version(app->protocol_version());

  msg_params["hmiLevel"] = static_cast<uint32_t>(app->hmi_level());

  msg_params["audioStreamingState"] =
      static_cast<uint32_t>(app->audio_streaming_state());

  msg_params["systemContext"] = static_cast<uint32_t>(app->system_context());

  msg->set_json_message(MessageHelper::ValueToString(msg_params));

  service()->SendMessageToMobile(msg);
}

void RemoteControlPlugin::SendResponseToMobile(
    application_manager::MessagePtr msg) {
  LOG4CXX_DEBUG(logger_, "Response to mobile: " << msg->json_message());
  service()->SendMessageToMobile(msg);
  request_controller_.DeleteRequest(msg->correlation_id());
}

void RemoteControlPlugin::SendTimeoutResponseToMobile(
    application_manager::MessagePtr msg) {
  LOG4CXX_DEBUG(
      logger_,
      "Timeout is expired. Response to mobile: " << msg->json_message());
  service()->SendMessageToMobile(msg);
}

void RemoteControlPlugin::RemoveAppExtensions() {
  std::vector<application_manager::ApplicationSharedPtr> applications =
      service()->GetApplications(GetModuleID());

  std::vector<application_manager::ApplicationSharedPtr>::iterator it =
      applications.begin();

  for (; it != applications.end(); ++it) {
    application_manager::ApplicationSharedPtr app = *it;
    if (app) {
      app->RemoveExtension(GetModuleID());
    }
  }
}

void RemoteControlPlugin::RemoveAppExtension(uint32_t app_id) {
  application_manager::ApplicationSharedPtr app =
      service()->GetApplication(app_id);

  if (app) {
    app->RemoveExtension(GetModuleID());
  }
}

bool RemoteControlPlugin::IsAppForPlugin(
    application_manager::ApplicationSharedPtr app) {
  LOG4CXX_AUTO_TRACE(logger_);
  application_manager::AppExtensionPtr app_extension =
      app->QueryInterface(GetModuleID());
  if (app_extension) {
    return true;
  }

  if (service()->IsRemoteControlApplication(app)) {
    RCAppExtensionPtr rc_app_extension = new RCAppExtension(GetModuleID());
    app->AddExtension(rc_app_extension);
    return true;
  }
  return false;
}

void RemoteControlPlugin::OnAppHMILevelChanged(
    application_manager::ApplicationSharedPtr app,
    mobile_apis::HMILevel::eType) {
  LOG4CXX_DEBUG(logger_,
                "RSDL application " << app->name().AsMBString()
                                    << " has changed hmi level to "
                                    << app->hmi_level());
  service()->NotifyHMIAboutHMILevel(app, app->hmi_level());
}

void RemoteControlPlugin::OnPluginServiceChanged() {
  LOG4CXX_AUTO_TRACE(logger_);
  const functional_modules::TimeUnit timeout_msec =
      service()->GetSettings().default_timeout();
  request_controller_.SetRequestTimeout(timeout_msec / 1000);
}

void RemoteControlPlugin::set_service(application_manager::ServicePtr service) {
  RemotePluginInterface::set_service(service);
  OnPluginServiceChanged();
}

RCEventDispatcher& RemoteControlPlugin::event_dispatcher() {
  return event_dispatcher_;
}

ResourceAllocationManager& RemoteControlPlugin::resource_allocation_manager() {
  return resource_allocation_manager_;
}

void RemoteControlPlugin::OnApplicationEvent(
    functional_modules::ApplicationEvent event,
    application_manager::ApplicationSharedPtr application) {
  LOG4CXX_AUTO_TRACE(logger_);
  if (false == service()->IsRemoteControlApplication(application)) {
    LOG4CXX_DEBUG(logger_,
                  "Application " << application->app_id()
                                 << " has no remote control functionality."
                                 << " Event will be ignored for RC plugin");
    return;
  }
  resource_allocation_manager_.OnApplicationEvent(event, application);
}

void RemoteControlPlugin::OnPolicyEvent(functional_modules::PolicyEvent event) {
  LOG4CXX_AUTO_TRACE(logger_);
  resource_allocation_manager_.OnPolicyEvent(event);
}

}  //  namespace remote_control
<|endoftext|>


<commit_before>#ifndef __RMOL_BUCKETLIST_HPP
#define __RMOL_BUCKETLIST_HPP

// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <list>
// RMOL
#include "Bucket.hpp"

namespace RMOL {

  /** Define a vector (ordered list) of N buckets/classes. */
  typedef std::list<Bucket> BucketList_T;

}
#endif // __RMOL_BUCKETLIST_HPP
<commit_msg>Moved the source files from the root directory into the sub-directories.<commit_after><|endoftext|>


<commit_before>// Copyright 2017 The NXT Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "backend/vulkan/CommandBufferVk.h"

#include "backend/Commands.h"
#include "backend/vulkan/BufferVk.h"
#include "backend/vulkan/FramebufferVk.h"
#include "backend/vulkan/RenderPassVk.h"
#include "backend/vulkan/RenderPipelineVk.h"
#include "backend/vulkan/TextureVk.h"
#include "backend/vulkan/VulkanBackend.h"

namespace backend { namespace vulkan {

    namespace {

        VkBufferImageCopy ComputeBufferImageCopyRegion(uint32_t rowPitch,
                                                       const BufferCopyLocation& bufferLocation,
                                                       const TextureCopyLocation& textureLocation) {
            const Texture* texture = ToBackend(textureLocation.texture).Get();

            VkBufferImageCopy region;

            region.bufferOffset = bufferLocation.offset;
            // In Vulkan the row length is in texels while it is in bytes for NXT
            region.bufferRowLength = rowPitch / TextureFormatPixelSize(texture->GetFormat());
            region.bufferImageHeight = rowPitch * textureLocation.height;

            region.imageSubresource.aspectMask = texture->GetVkAspectMask();
            region.imageSubresource.mipLevel = textureLocation.level;
            region.imageSubresource.baseArrayLayer = 0;
            region.imageSubresource.layerCount = 1;

            region.imageOffset.x = textureLocation.x;
            region.imageOffset.y = textureLocation.y;
            region.imageOffset.z = textureLocation.z;

            region.imageExtent.width = textureLocation.width;
            region.imageExtent.height = textureLocation.height;
            region.imageExtent.depth = textureLocation.depth;

            return region;
        }

    }  // anonymous namespace

    CommandBuffer::CommandBuffer(CommandBufferBuilder* builder)
        : CommandBufferBase(builder), mCommands(builder->AcquireCommands()) {
    }

    CommandBuffer::~CommandBuffer() {
        FreeCommands(&mCommands);
    }

    void CommandBuffer::RecordCommands(VkCommandBuffer commands) {
        Device* device = ToBackend(GetDevice());

        Command type;
        while (mCommands.NextCommandId(&type)) {
            switch (type) {
                case Command::CopyBufferToBuffer: {
                    CopyBufferToBufferCmd* copy = mCommands.NextCommand<CopyBufferToBufferCmd>();
                    auto& src = copy->source;
                    auto& dst = copy->destination;

                    VkBufferCopy region;
                    region.srcOffset = src.offset;
                    region.dstOffset = dst.offset;
                    region.size = copy->size;

                    VkBuffer srcHandle = ToBackend(src.buffer)->GetHandle();
                    VkBuffer dstHandle = ToBackend(dst.buffer)->GetHandle();
                    device->fn.CmdCopyBuffer(commands, srcHandle, dstHandle, 1, &region);
                } break;

                case Command::CopyBufferToTexture: {
                    CopyBufferToTextureCmd* copy = mCommands.NextCommand<CopyBufferToTextureCmd>();
                    auto& src = copy->source;
                    auto& dst = copy->destination;

                    VkBuffer srcBuffer = ToBackend(src.buffer)->GetHandle();
                    VkImage dstImage = ToBackend(dst.texture)->GetHandle();
                    VkBufferImageCopy region =
                        ComputeBufferImageCopyRegion(copy->rowPitch, src, dst);

                    // The image is written to so the NXT guarantees make sure it is in the
                    // TRANSFER_DST_OPTIMAL layout
                    device->fn.CmdCopyBufferToImage(commands, srcBuffer, dstImage,
                                                    VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1,
                                                    &region);
                } break;

                case Command::CopyTextureToBuffer: {
                    CopyTextureToBufferCmd* copy = mCommands.NextCommand<CopyTextureToBufferCmd>();
                    auto& src = copy->source;
                    auto& dst = copy->destination;

                    VkImage srcImage = ToBackend(src.texture)->GetHandle();
                    VkBuffer dstBuffer = ToBackend(dst.buffer)->GetHandle();
                    VkBufferImageCopy region =
                        ComputeBufferImageCopyRegion(copy->rowPitch, dst, src);

                    // The NXT TransferSrc usage is always mapped to GENERAL
                    device->fn.CmdCopyImageToBuffer(commands, srcImage, VK_IMAGE_LAYOUT_GENERAL,
                                                    dstBuffer, 1, &region);
                } break;

                case Command::BeginRenderPass: {
                    BeginRenderPassCmd* cmd = mCommands.NextCommand<BeginRenderPassCmd>();
                    Framebuffer* framebuffer = ToBackend(cmd->framebuffer.Get());
                    RenderPass* renderPass = ToBackend(cmd->renderPass.Get());

                    ASSERT(renderPass->GetSubpassCount() == 1);
                    ASSERT(renderPass->GetAttachmentCount() <= kMaxColorAttachments + 1);

                    std::array<VkClearValue, kMaxColorAttachments + 1> clearValues;
                    framebuffer->FillClearValues(clearValues.data());

                    VkRenderPassBeginInfo beginInfo;
                    beginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
                    beginInfo.pNext = nullptr;
                    beginInfo.renderPass = renderPass->GetHandle();
                    beginInfo.framebuffer = framebuffer->GetHandle();
                    beginInfo.renderArea.offset.x = 0;
                    beginInfo.renderArea.offset.y = 0;
                    beginInfo.renderArea.extent.width = framebuffer->GetWidth();
                    beginInfo.renderArea.extent.height = framebuffer->GetHeight();
                    beginInfo.clearValueCount = renderPass->GetAttachmentCount();
                    beginInfo.pClearValues = clearValues.data();

                    device->fn.CmdBeginRenderPass(commands, &beginInfo, VK_SUBPASS_CONTENTS_INLINE);

                    // Set all the dynamic state just in case.
                    device->fn.CmdSetLineWidth(commands, 1.0f);
                    device->fn.CmdSetDepthBounds(commands, 0.0f, 1.0f);

                    float blendConstants[4] = {
                        1.0f,
                        1.0f,
                        1.0f,
                        1.0f,
                    };
                    device->fn.CmdSetBlendConstants(commands, blendConstants);

                    device->fn.CmdSetStencilCompareMask(commands, VK_STENCIL_FRONT_AND_BACK, 0);
                    device->fn.CmdSetStencilWriteMask(commands, VK_STENCIL_FRONT_AND_BACK, 0);
                    device->fn.CmdSetStencilReference(commands, VK_STENCIL_FRONT_AND_BACK, 0);

                    // The viewport and scissor default to cover all of the attachments
                    VkViewport viewport;
                    viewport.x = 0.0f;
                    viewport.y = 0.0f;
                    viewport.width = static_cast<float>(framebuffer->GetWidth());
                    viewport.height = static_cast<float>(framebuffer->GetHeight());
                    viewport.minDepth = 0.0f;
                    viewport.maxDepth = 1.0f;
                    device->fn.CmdSetViewport(commands, 0, 1, &viewport);

                    VkRect2D scissorRect;
                    scissorRect.offset.x = 0;
                    scissorRect.offset.y = 0;
                    scissorRect.extent.width = framebuffer->GetWidth();
                    scissorRect.extent.height = framebuffer->GetHeight();
                    device->fn.CmdSetScissor(commands, 0, 1, &scissorRect);
                } break;

                case Command::BeginRenderSubpass: {
                    mCommands.NextCommand<BeginRenderSubpassCmd>();
                    // Do nothing because the single subpass is started in vkBeginRenderPass
                } break;

                case Command::DrawArrays: {
                    DrawArraysCmd* draw = mCommands.NextCommand<DrawArraysCmd>();

                    device->fn.CmdDraw(commands, draw->vertexCount, draw->instanceCount,
                                       draw->firstVertex, draw->firstInstance);
                } break;

                case Command::DrawElements: {
                    DrawElementsCmd* draw = mCommands.NextCommand<DrawElementsCmd>();

                    uint32_t vertexOffset = 0;
                    device->fn.CmdDrawIndexed(commands, draw->indexCount, draw->instanceCount,
                                              draw->firstIndex, vertexOffset, draw->firstInstance);
                } break;

                case Command::EndRenderPass: {
                    mCommands.NextCommand<EndRenderPassCmd>();
                    device->fn.CmdEndRenderPass(commands);
                } break;

                case Command::EndRenderSubpass: {
                    mCommands.NextCommand<EndRenderSubpassCmd>();
                    // Do nothing because the single subpass is ended in vkEndRenderPass
                } break;

                case Command::SetIndexBuffer: {
                    SetIndexBufferCmd* cmd = mCommands.NextCommand<SetIndexBufferCmd>();
                    VkBuffer indexBuffer = ToBackend(cmd->buffer)->GetHandle();

                    // TODO(cwallez@chromium.org): get the index type from the last render pipeline
                    // and rebind if needed on pipeline change
                    device->fn.CmdBindIndexBuffer(commands, indexBuffer,
                                                  static_cast<VkDeviceSize>(cmd->offset),
                                                  VK_INDEX_TYPE_UINT16);
                } break;

                case Command::SetRenderPipeline: {
                    SetRenderPipelineCmd* cmd = mCommands.NextCommand<SetRenderPipelineCmd>();
                    RenderPipeline* pipeline = ToBackend(cmd->pipeline).Get();

                    device->fn.CmdBindPipeline(commands, VK_PIPELINE_BIND_POINT_GRAPHICS,
                                               pipeline->GetHandle());
                } break;

                case Command::SetVertexBuffers: {
                    SetVertexBuffersCmd* cmd = mCommands.NextCommand<SetVertexBuffersCmd>();
                    auto buffers = mCommands.NextData<Ref<BufferBase>>(cmd->count);
                    auto offsets = mCommands.NextData<uint32_t>(cmd->count);

                    std::array<VkBuffer, kMaxVertexInputs> vkBuffers;
                    std::array<VkDeviceSize, kMaxVertexInputs> vkOffsets;

                    for (uint32_t i = 0; i < cmd->count; ++i) {
                        Buffer* buffer = ToBackend(buffers[i].Get());
                        vkBuffers[i] = buffer->GetHandle();
                        vkOffsets[i] = static_cast<VkDeviceSize>(offsets[i]);
                    }

                    device->fn.CmdBindVertexBuffers(commands, cmd->startSlot, cmd->count,
                                                    vkBuffers.data(), vkOffsets.data());
                } break;

                case Command::TransitionBufferUsage: {
                    TransitionBufferUsageCmd* cmd =
                        mCommands.NextCommand<TransitionBufferUsageCmd>();

                    Buffer* buffer = ToBackend(cmd->buffer.Get());
                    buffer->RecordBarrier(commands, buffer->GetUsage(), cmd->usage);
                    buffer->UpdateUsageInternal(cmd->usage);
                } break;

                case Command::TransitionTextureUsage: {
                    TransitionTextureUsageCmd* cmd =
                        mCommands.NextCommand<TransitionTextureUsageCmd>();

                    Texture* texture = ToBackend(cmd->texture.Get());
                    texture->RecordBarrier(commands, texture->GetUsage(), cmd->usage);
                    texture->UpdateUsageInternal(cmd->usage);
                } break;

                default: { UNREACHABLE(); } break;
            }
        }
    }

}}  // namespace backend::vulkan
<commit_msg>Vulkan: transition attachments implicitly<commit_after>// Copyright 2017 The NXT Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "backend/vulkan/CommandBufferVk.h"

#include "backend/Commands.h"
#include "backend/vulkan/BufferVk.h"
#include "backend/vulkan/FramebufferVk.h"
#include "backend/vulkan/RenderPassVk.h"
#include "backend/vulkan/RenderPipelineVk.h"
#include "backend/vulkan/TextureVk.h"
#include "backend/vulkan/VulkanBackend.h"

namespace backend { namespace vulkan {

    namespace {

        VkBufferImageCopy ComputeBufferImageCopyRegion(uint32_t rowPitch,
                                                       const BufferCopyLocation& bufferLocation,
                                                       const TextureCopyLocation& textureLocation) {
            const Texture* texture = ToBackend(textureLocation.texture).Get();

            VkBufferImageCopy region;

            region.bufferOffset = bufferLocation.offset;
            // In Vulkan the row length is in texels while it is in bytes for NXT
            region.bufferRowLength = rowPitch / TextureFormatPixelSize(texture->GetFormat());
            region.bufferImageHeight = rowPitch * textureLocation.height;

            region.imageSubresource.aspectMask = texture->GetVkAspectMask();
            region.imageSubresource.mipLevel = textureLocation.level;
            region.imageSubresource.baseArrayLayer = 0;
            region.imageSubresource.layerCount = 1;

            region.imageOffset.x = textureLocation.x;
            region.imageOffset.y = textureLocation.y;
            region.imageOffset.z = textureLocation.z;

            region.imageExtent.width = textureLocation.width;
            region.imageExtent.height = textureLocation.height;
            region.imageExtent.depth = textureLocation.depth;

            return region;
        }

    }  // anonymous namespace

    CommandBuffer::CommandBuffer(CommandBufferBuilder* builder)
        : CommandBufferBase(builder), mCommands(builder->AcquireCommands()) {
    }

    CommandBuffer::~CommandBuffer() {
        FreeCommands(&mCommands);
    }

    void CommandBuffer::RecordCommands(VkCommandBuffer commands) {
        Device* device = ToBackend(GetDevice());

        Command type;
        while (mCommands.NextCommandId(&type)) {
            switch (type) {
                case Command::CopyBufferToBuffer: {
                    CopyBufferToBufferCmd* copy = mCommands.NextCommand<CopyBufferToBufferCmd>();
                    auto& src = copy->source;
                    auto& dst = copy->destination;

                    VkBufferCopy region;
                    region.srcOffset = src.offset;
                    region.dstOffset = dst.offset;
                    region.size = copy->size;

                    VkBuffer srcHandle = ToBackend(src.buffer)->GetHandle();
                    VkBuffer dstHandle = ToBackend(dst.buffer)->GetHandle();
                    device->fn.CmdCopyBuffer(commands, srcHandle, dstHandle, 1, &region);
                } break;

                case Command::CopyBufferToTexture: {
                    CopyBufferToTextureCmd* copy = mCommands.NextCommand<CopyBufferToTextureCmd>();
                    auto& src = copy->source;
                    auto& dst = copy->destination;

                    VkBuffer srcBuffer = ToBackend(src.buffer)->GetHandle();
                    VkImage dstImage = ToBackend(dst.texture)->GetHandle();
                    VkBufferImageCopy region =
                        ComputeBufferImageCopyRegion(copy->rowPitch, src, dst);

                    // The image is written to so the NXT guarantees make sure it is in the
                    // TRANSFER_DST_OPTIMAL layout
                    device->fn.CmdCopyBufferToImage(commands, srcBuffer, dstImage,
                                                    VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1,
                                                    &region);
                } break;

                case Command::CopyTextureToBuffer: {
                    CopyTextureToBufferCmd* copy = mCommands.NextCommand<CopyTextureToBufferCmd>();
                    auto& src = copy->source;
                    auto& dst = copy->destination;

                    VkImage srcImage = ToBackend(src.texture)->GetHandle();
                    VkBuffer dstBuffer = ToBackend(dst.buffer)->GetHandle();
                    VkBufferImageCopy region =
                        ComputeBufferImageCopyRegion(copy->rowPitch, dst, src);

                    // The NXT TransferSrc usage is always mapped to GENERAL
                    device->fn.CmdCopyImageToBuffer(commands, srcImage, VK_IMAGE_LAYOUT_GENERAL,
                                                    dstBuffer, 1, &region);
                } break;

                case Command::BeginRenderPass: {
                    BeginRenderPassCmd* cmd = mCommands.NextCommand<BeginRenderPassCmd>();
                    Framebuffer* framebuffer = ToBackend(cmd->framebuffer.Get());
                    RenderPass* renderPass = ToBackend(cmd->renderPass.Get());

                    // NXT has an implicit transition to color attachment on subpasses. Transition
                    // the attachments now before we start the render pass.
                    for (uint32_t i = 0; i < renderPass->GetAttachmentCount(); ++i) {
                        Texture* attachment =
                            ToBackend(framebuffer->GetTextureView(i)->GetTexture());
                        attachment->RecordBarrier(commands, attachment->GetUsage(),
                                                  nxt::TextureUsageBit::OutputAttachment);
                        attachment->UpdateUsageInternal(nxt::TextureUsageBit::OutputAttachment);
                    }

                    ASSERT(renderPass->GetSubpassCount() == 1);
                    ASSERT(renderPass->GetAttachmentCount() <= kMaxColorAttachments + 1);

                    std::array<VkClearValue, kMaxColorAttachments + 1> clearValues;
                    framebuffer->FillClearValues(clearValues.data());

                    VkRenderPassBeginInfo beginInfo;
                    beginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
                    beginInfo.pNext = nullptr;
                    beginInfo.renderPass = renderPass->GetHandle();
                    beginInfo.framebuffer = framebuffer->GetHandle();
                    beginInfo.renderArea.offset.x = 0;
                    beginInfo.renderArea.offset.y = 0;
                    beginInfo.renderArea.extent.width = framebuffer->GetWidth();
                    beginInfo.renderArea.extent.height = framebuffer->GetHeight();
                    beginInfo.clearValueCount = renderPass->GetAttachmentCount();
                    beginInfo.pClearValues = clearValues.data();

                    device->fn.CmdBeginRenderPass(commands, &beginInfo, VK_SUBPASS_CONTENTS_INLINE);

                    // Set all the dynamic state just in case.
                    device->fn.CmdSetLineWidth(commands, 1.0f);
                    device->fn.CmdSetDepthBounds(commands, 0.0f, 1.0f);

                    float blendConstants[4] = {
                        1.0f,
                        1.0f,
                        1.0f,
                        1.0f,
                    };
                    device->fn.CmdSetBlendConstants(commands, blendConstants);

                    device->fn.CmdSetStencilCompareMask(commands, VK_STENCIL_FRONT_AND_BACK, 0);
                    device->fn.CmdSetStencilWriteMask(commands, VK_STENCIL_FRONT_AND_BACK, 0);
                    device->fn.CmdSetStencilReference(commands, VK_STENCIL_FRONT_AND_BACK, 0);

                    // The viewport and scissor default to cover all of the attachments
                    VkViewport viewport;
                    viewport.x = 0.0f;
                    viewport.y = 0.0f;
                    viewport.width = static_cast<float>(framebuffer->GetWidth());
                    viewport.height = static_cast<float>(framebuffer->GetHeight());
                    viewport.minDepth = 0.0f;
                    viewport.maxDepth = 1.0f;
                    device->fn.CmdSetViewport(commands, 0, 1, &viewport);

                    VkRect2D scissorRect;
                    scissorRect.offset.x = 0;
                    scissorRect.offset.y = 0;
                    scissorRect.extent.width = framebuffer->GetWidth();
                    scissorRect.extent.height = framebuffer->GetHeight();
                    device->fn.CmdSetScissor(commands, 0, 1, &scissorRect);
                } break;

                case Command::BeginRenderSubpass: {
                    mCommands.NextCommand<BeginRenderSubpassCmd>();
                    // Do nothing because the single subpass is started in vkBeginRenderPass
                } break;

                case Command::DrawArrays: {
                    DrawArraysCmd* draw = mCommands.NextCommand<DrawArraysCmd>();

                    device->fn.CmdDraw(commands, draw->vertexCount, draw->instanceCount,
                                       draw->firstVertex, draw->firstInstance);
                } break;

                case Command::DrawElements: {
                    DrawElementsCmd* draw = mCommands.NextCommand<DrawElementsCmd>();

                    uint32_t vertexOffset = 0;
                    device->fn.CmdDrawIndexed(commands, draw->indexCount, draw->instanceCount,
                                              draw->firstIndex, vertexOffset, draw->firstInstance);
                } break;

                case Command::EndRenderPass: {
                    mCommands.NextCommand<EndRenderPassCmd>();
                    device->fn.CmdEndRenderPass(commands);
                } break;

                case Command::EndRenderSubpass: {
                    mCommands.NextCommand<EndRenderSubpassCmd>();
                    // Do nothing because the single subpass is ended in vkEndRenderPass
                } break;

                case Command::SetIndexBuffer: {
                    SetIndexBufferCmd* cmd = mCommands.NextCommand<SetIndexBufferCmd>();
                    VkBuffer indexBuffer = ToBackend(cmd->buffer)->GetHandle();

                    // TODO(cwallez@chromium.org): get the index type from the last render pipeline
                    // and rebind if needed on pipeline change
                    device->fn.CmdBindIndexBuffer(commands, indexBuffer,
                                                  static_cast<VkDeviceSize>(cmd->offset),
                                                  VK_INDEX_TYPE_UINT16);
                } break;

                case Command::SetRenderPipeline: {
                    SetRenderPipelineCmd* cmd = mCommands.NextCommand<SetRenderPipelineCmd>();
                    RenderPipeline* pipeline = ToBackend(cmd->pipeline).Get();

                    device->fn.CmdBindPipeline(commands, VK_PIPELINE_BIND_POINT_GRAPHICS,
                                               pipeline->GetHandle());
                } break;

                case Command::SetVertexBuffers: {
                    SetVertexBuffersCmd* cmd = mCommands.NextCommand<SetVertexBuffersCmd>();
                    auto buffers = mCommands.NextData<Ref<BufferBase>>(cmd->count);
                    auto offsets = mCommands.NextData<uint32_t>(cmd->count);

                    std::array<VkBuffer, kMaxVertexInputs> vkBuffers;
                    std::array<VkDeviceSize, kMaxVertexInputs> vkOffsets;

                    for (uint32_t i = 0; i < cmd->count; ++i) {
                        Buffer* buffer = ToBackend(buffers[i].Get());
                        vkBuffers[i] = buffer->GetHandle();
                        vkOffsets[i] = static_cast<VkDeviceSize>(offsets[i]);
                    }

                    device->fn.CmdBindVertexBuffers(commands, cmd->startSlot, cmd->count,
                                                    vkBuffers.data(), vkOffsets.data());
                } break;

                case Command::TransitionBufferUsage: {
                    TransitionBufferUsageCmd* cmd =
                        mCommands.NextCommand<TransitionBufferUsageCmd>();

                    Buffer* buffer = ToBackend(cmd->buffer.Get());
                    buffer->RecordBarrier(commands, buffer->GetUsage(), cmd->usage);
                    buffer->UpdateUsageInternal(cmd->usage);
                } break;

                case Command::TransitionTextureUsage: {
                    TransitionTextureUsageCmd* cmd =
                        mCommands.NextCommand<TransitionTextureUsageCmd>();

                    Texture* texture = ToBackend(cmd->texture.Get());
                    texture->RecordBarrier(commands, texture->GetUsage(), cmd->usage);
                    texture->UpdateUsageInternal(cmd->usage);
                } break;

                default: { UNREACHABLE(); } break;
            }
        }
    }

}}  // namespace backend::vulkan
<|endoftext|>


<commit_before>#ifndef ATL_PRINT_HH
#define ATL_PRINT_HH
/**
 * @file /home/ryan/programming/atl/print.hpp
 * @author Ryan Domigan <ryan_domigan@sutdents@uml.edu>
 * Created on Aug 10, 2013
 */
#include <functional>
#include <iostream>
#include <utility>

#include "./utility.hpp"
#include "./helpers.hpp"

namespace atl {
    namespace printer {
	struct Printer {
	    virtual std::ostream& print(std::ostream&) const = 0;
	};

	template<class Container>
	struct PrintRange : public Printer {
	    Range<typename Container::const_iterator> _range;
	    char _delim_open, _delim_close;

	    PrintRange(const Container& range, char delim_open, char delim_close)
		: _range(range.begin(), range.end()),
		  _delim_open(delim_open),
		  _delim_close(delim_close) {}

	    virtual std::ostream& print(std::ostream&) const;
	};

	struct PrintAny : public Printer {
	    const Any &a;
	    PrintAny(const Any &a_) : a(a_) {}
	    virtual std::ostream& print(std::ostream&) const;
	};

	template<class Range>
	PrintRange<Range> range(const Range& rr, char open='(', char close=')') {
	    return PrintRange<Range>(rr, open, close);
	}
	PrintAny any(const Any& aa) { return PrintAny(aa); }

	void print_atom_debug(const Any& vv, std::ostream& out) {
	    out << "@" << &vv
		<< " [" << type_name(vv._tag) << ":" << vv.value << "]"
		<< endl;
	}

	struct DebugRange : public Printer {
	    Range<const Any*> _rr;
	    bool _line_numbers;

	    DebugRange(Range<const Any*> rr) : _rr(rr) , _line_numbers(false) {}
	    DebugRange(Range<const Any*> rr, bool line_numbers) :
		_rr(rr) , _line_numbers(line_numbers) {}

	    virtual std::ostream& print(std::ostream& out) const {
		size_t line = 0;
		for(auto& vv: _rr) {
		    if(_line_numbers) { out << line << ": ";
			                ++line; }
		    print_atom_debug(vv, out);
		}
		return out;
	    }
	};

	template<class Range>
	DebugRange debug_range(const Range& rr) {
	    return DebugRange(rr);
	}

	DebugRange debug_range(const Any& rr) {
	    using namespace flat_iterator;
	    return DebugRange(make_range(const_begin(rr) - 2, const_end(rr)));
	}

	DebugRange debug_range(const Any& rr, bool line_numbers) {
	    using namespace flat_iterator;
	    return DebugRange(make_range(const_begin(rr) - 2, const_end(rr)), line_numbers);
	}

	std::ostream& operator<<(std::ostream& out, const printer::Printer& p) { return p.print(out); }

	template<class Container>
	std::ostream& PrintRange<Container>::print(std::ostream& out) const {
	    if(_range.empty())
		return out << _delim_open << _delim_close << endl;
	    else {
		out << _delim_open << printer::any(_range[0]) << flush;
		for(auto& vv : slice(_range, 1)) out << " " << printer::any(vv);
		return out << _delim_close;
	    }
	}

	std::ostream& PrintAny::print(std::ostream& out) const {
	    auto trim_addr = [](void *pntr) {
		return reinterpret_cast<long>(pntr) & (256 - 1);
	    };

	    using namespace std;
	    switch(a._tag) {
	    case tag<Undefined>::value:
		return out << "#<Undefined:" << hex << trim_addr(a.value) << ">";

	    case tag<Symbol>::value:
                return out << "'" << unwrap<string>(a);

	    case tag<Fixnum>::value:
		return out << value<Fixnum>(a);
	    case tag<Bool>::value:
		if(value<bool>(a))
		    return out << "True";
		else
		    return out << "False";
	    case tag<String>::value:
		return out << '"' << *reinterpret_cast<string*>(a.value) << '"';
	    case tag<PrimitiveRecursive>::value:
		return out << unwrap<PrimitiveRecursive>(a)._name;
	    case tag<Pointer>::value:
		if(a.value)
		    return out << "#<Pointer-" << hex << (reinterpret_cast<long>(a.value) & (256 - 1)) << ">";
		else
		    return out << "#<Pointer-NULL>";
	    case tag<Data>::value:
		return out << "'" << range(unwrap<Data>(a));
	    case tag<Ast>::value:
		return out << range(unwrap<Ast>(a));
	    case tag<Slice>::value:
		return out << range(unwrap<Slice>(a), '[', ']');
	    case tag<CxxArray>::value:
		return out << range(unwrap<CxxArray>(a));
		return out << "#" << range(unwrap<Data>(a));
	    case tag<Procedure>::value:
		return out << "#<\\ "
			   << ">" << flush;
	    default:
		return out << "#<" << type_name(a._tag) << ">";
	    }}
    }
}

#endif
<commit_msg>Add a non-template print function for debugging<commit_after>#ifndef ATL_PRINT_HH
#define ATL_PRINT_HH
/**
 * @file /home/ryan/programming/atl/print.hpp
 * @author Ryan Domigan <ryan_domigan@sutdents@uml.edu>
 * Created on Aug 10, 2013
 */
#include <functional>
#include <iostream>
#include <utility>

#include "./utility.hpp"
#include "./helpers.hpp"

namespace atl {
    namespace printer {
	struct Printer {
	    virtual std::ostream& print(std::ostream&) const = 0;
	};

	template<class Container>
	struct PrintRange : public Printer {
	    Range<typename Container::const_iterator> _range;
	    char _delim_open, _delim_close;

	    PrintRange(const Container& range, char delim_open, char delim_close)
		: _range(range.begin(), range.end()),
		  _delim_open(delim_open),
		  _delim_close(delim_close) {}

	    virtual std::ostream& print(std::ostream&) const;
	};

	struct PrintAny : public Printer {
	    const Any &a;
	    PrintAny(const Any &a_) : a(a_) {}
	    virtual std::ostream& print(std::ostream&) const;
	};

	template<class Range>
	PrintRange<Range> range(const Range& rr, char open='(', char close=')') {
	    return PrintRange<Range>(rr, open, close);
	}
	PrintAny any(const Any& aa) { return PrintAny(aa); }

	void print_atom_debug(const Any& vv, std::ostream& out) {
	    out << "@" << &vv
		<< " [" << type_name(vv._tag) << ":" << vv.value << "]"
		<< endl;
	}

	struct DebugRange : public Printer {
	    Range<const Any*> _rr;
	    bool _line_numbers;

	    DebugRange(Range<const Any*> rr) : _rr(rr) , _line_numbers(false) {}
	    DebugRange(Range<const Any*> rr, bool line_numbers) :
		_rr(rr) , _line_numbers(line_numbers) {}

	    virtual std::ostream& print(std::ostream& out) const {
		size_t line = 0;
		for(auto& vv: _rr) {
		    if(_line_numbers) { out << line << ": ";
			                ++line; }
		    print_atom_debug(vv, out);
		}
		return out;
	    }
	};

	template<class Range>
	DebugRange debug_range(const Range& rr) {
	    return DebugRange(rr);
	}

	DebugRange debug_range(const Any& rr) {
	    using namespace flat_iterator;
	    return DebugRange(make_range(const_begin(rr) - 2, const_end(rr)));
	}

	DebugRange debug_range(const Any& rr, bool line_numbers) {
	    using namespace flat_iterator;
	    return DebugRange(make_range(const_begin(rr) - 2, const_end(rr)), line_numbers);
	}

	std::ostream& operator<<(std::ostream& out, const printer::Printer& p) { return p.print(out); }

	template<class Container>
	std::ostream& PrintRange<Container>::print(std::ostream& out) const {
	    if(_range.empty())
		return out << _delim_open << _delim_close << endl;
	    else {
		out << _delim_open << printer::any(_range[0]) << flush;
		for(auto& vv : slice(_range, 1)) out << " " << printer::any(vv);
		return out << _delim_close;
	    }
	}

	std::ostream& PrintAny::print(std::ostream& out) const {
	    auto trim_addr = [](void *pntr) {
		return reinterpret_cast<long>(pntr) & (256 - 1);
	    };

	    using namespace std;
	    switch(a._tag) {
	    case tag<Undefined>::value:
		return out << "#<Undefined:" << hex << trim_addr(a.value) << ">";

	    case tag<Symbol>::value:
                return out << "'" << unwrap<string>(a);

	    case tag<Fixnum>::value:
		return out << value<Fixnum>(a);
	    case tag<Bool>::value:
		if(value<bool>(a))
		    return out << "True";
		else
		    return out << "False";
	    case tag<String>::value:
		return out << '"' << *reinterpret_cast<string*>(a.value) << '"';
	    case tag<PrimitiveRecursive>::value:
		return out << unwrap<PrimitiveRecursive>(a)._name;
	    case tag<Pointer>::value:
		if(a.value)
		    return out << "#<Pointer-" << hex << (reinterpret_cast<long>(a.value) & (256 - 1)) << ">";
		else
		    return out << "#<Pointer-NULL>";
	    case tag<Data>::value:
		return out << "'" << range(unwrap<Data>(a));
	    case tag<Ast>::value:
		return out << range(unwrap<Ast>(a));
	    case tag<Slice>::value:
		return out << range(unwrap<Slice>(a), '[', ']');
	    case tag<CxxArray>::value:
		return out << range(unwrap<CxxArray>(a));
		return out << "#" << range(unwrap<Data>(a));
	    case tag<Procedure>::value:
		return out << "#<\\ "
			   << ">" << flush;
	    default:
		return out << "#<" << type_name(a._tag) << ">";
	    }}
    }

    void dbg_print_any(Any vv) {
        cout << printer::any(vv) << endl;
    }
}

#endif
<|endoftext|>