<commit_before>////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//  Name: DMAnalysis.cxx                                                      //
//                                                                            //
//  Creator: Andrew Hard                                                      //
//  Email: ahard@cern.ch                                                      //
//  Date: 15/04/2015                                                          //
//                                                                            //
//  This namespace stores all of the global information for the H->gg + DM    //
//  search with 13 TeV data in 2015. It also has all of the includes that are //
//  necessary for the analysis.                                               //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

#include "DMAnalysis.h"

/**
   -----------------------------------------------------------------------------
   Convert the DM sample name into a process name, a subset of the full name.
   @param modeName - the name of the DM production mode.
   @param processName - the name of the process.
*/
TString DMAnalysis::getMediatorName(TString modeName) {
  if (modeName.Contains("shxx_gg")) return "shxx_gg";
  else if (modeName.Contains("zphxx_gg")) return "zphxx_gg";
  else if (modeName.Contains("zp2hdmxx_gg")) return "zp2hdmxx_gg";
  else {
    std::cout << "Analysis Error: no matching mediator name: "
	      << modeName << std::endl;
    exit(0);
  }
}

/**
   -----------------------------------------------------------------------------
   Convert the DM sample name into a process name, a subset of the full name.
   @param modeName - the name of the DM production mode.
   @param processName - the name of the process.
*/
TString DMAnalysis::getPrintMediatorName(TString modeName) {
  if (modeName.Contains("shxx_gg")) return "Scalar";
  else if (modeName.Contains("zphxx_gg")) return "Z'";
  else if (modeName.Contains("zp2hdmxx_gg")) return "Z_{2HDM}'";
  else {
    std::cout << "Analysis Error: no matching mediator name: "
	      << modeName << std::endl;
    exit(0);
  }
}

/**
   -----------------------------------------------------------------------------
   Get a pretty LaTex formatted name for a variable.
   @param sampleName - The name of the sample.
   @returns - A LaTex formatted TString.
*/
TString DMAnalysis::getPrintSampleName(Config *config, TString sampleName) {
  if (sampleName.EqualTo("gg")) return "#it{#gamma#gamma}";
  else if (sampleName.EqualTo("gjet")) return "#it{#gamma}+jet";
  else if (sampleName.EqualTo("SMHiggs")) {
    return "SM #it{H#rightarrow#gamma#gamma}";
  }
  else if (sampleName.EqualTo("yy")) return "#it{#gamma#gamma}";
  else if (sampleName.EqualTo("yjet")) return "#it{#gamma}+jet";
  else if (sampleName.EqualTo("jj")) return "di-jet";
  else if (sampleName.EqualTo("Zyy")) return "#it{Z#gamma#gamma}";
  else if (sampleName.EqualTo("Wyy")) return "#it{W#gamma#gamma}";
  else if (sampleName.EqualTo("Zy")) return "#it{Z#gamma}";
  else if (sampleName.EqualTo("Wy")) return "#it{W#gamma}";
  else if (sampleName.EqualTo("ttbar")) return "#it{t#bar{t}}";
  else if (sampleName.EqualTo("diboson")) return "#it{WW}+#it{WZ}+#it{ZZ}";
  else if (sampleName.EqualTo("ggH")) {
    return "#it{ggH(#rightarrow#gamma#gamma)}";
  }
  else if (sampleName.EqualTo("VBF")) {
    return "#it{VBF (H#rightarrow#gamma#gamma)}";
  }
  else if (sampleName.EqualTo("WH")) {
    return "#it{WH(#rightarrow#gamma#gamma)}";
  }
  else if (sampleName.EqualTo("ZH")) {
    return "#it{ZH(#rightarrow#gamma#gamma)}";
  }
  else if (sampleName.EqualTo("bbH")) {
    return "#it{b#bar{b}H(#rightarrow#gamma#gamma)}";
  }
  else if (sampleName.EqualTo("ttH")) {
    return "#it{t#bar{t}H(#rightarrow#gamma#gamma)}";
  }
  else if (DMAnalysis::isDMSample(config, sampleName)) {
    TString mediatorName = DMAnalysis::getMediatorName(sampleName);
    int mediatorMass = DMAnalysis::getMediatorMass(config, sampleName);
    TString medMassForm;
    if (mediatorName.EqualTo("shxx_gg")) {
      medMassForm = Form("#it{m_{S}}=%dGeV", mediatorMass);
    }
    else if (mediatorName.EqualTo("zphxx_gg")) {
      medMassForm = Form("#it{m_{Z'}}=%dGeV", mediatorMass);
    }
    else if (mediatorName.EqualTo("zp2hdmxx_gg")) {
      medMassForm = Form("#it{m_{Z'}}=%dGeV", mediatorMass);
    }

    int darkMatterMass = DMAnalysis::getDarkMatterMass(config, sampleName);
    TString darkMassForm;
    if (mediatorName.EqualTo("shxx_gg")) {
      darkMassForm = Form("#it{m_{#chi}}=%dGeV", darkMatterMass);
    }
    else if (mediatorName.EqualTo("zphxx_gg")) {
      darkMassForm = Form("#it{m_{#chi}}=%dGeV", darkMatterMass);
    }
    else if (mediatorName.EqualTo("zp2hdmxx_gg")) {
      darkMassForm = Form("#it{m_{A}}=%dGeV", darkMatterMass);
    }
    //(DMAnalysis::getPrintMediatorName(sampleName)).Data(),
    TString newName = Form("%s %s", medMassForm.Data(), darkMassForm.Data());
    return newName;
  }
  else return sampleName;
}

/**
   -----------------------------------------------------------------------------
   Get a pretty LaTex formatted name for a variable.
   @param varName - The name of the variable in the file.
   @returns - A LaTex formatted TString.
*/
TString DMAnalysis::getPrintVarName(TString varName) {
  varName.ToLower();
  varName = varName.ReplaceAll("anacut", "");
  if (varName.EqualTo("ptyy") || varName.EqualTo("diphotonpt")) {
    return "p_{T}^{#gamma#gamma} [GeV]";
  }
  else if (varName.EqualTo("etmiss")) return "#slash{E}_{T} [GeV]";
  else if (varName.EqualTo("ratioetmissptyy")) {
    return "#slash{E}_{T}/p_{T}^{#gamma#gamma}";
  }
  else if (varName.EqualTo("myy")) return "M_{#gamma#gamma} [GeV]";
  else if (varName.Contains("atanratio")) {
    return "tan^{-1}(#slash{E}_{T}/p_{T}^{#gamma#gamma})";
  }
  else if (varName.EqualTo("sumsqrtetmissptyy")) {
    return "#sqrt{(p_{T}^{#gamma#gamma})^{2} + (#slash{E}_{T})^{2}} [GeV]";
  }
  else if (varName.Contains("dphiyyetmiss")) {
    return "#Delta#phi(#gamma#gamma-#slash{E}_{T})";
  }
  else if (varName.Contains("njets")) return "N_{Jets}";
  else if (varName.Contains("nleptons")) return "N_{Leptons}";
  else if (varName.Contains("p0")) {
    if (varName.Contains("exp")) return "p_{0} exp.";
    else if (varName.Contains("obs")) return "p_{0} obs.";
    else return "p_{0}";
  }
  else if (varName.Contains("cl")) {
    if (varName.Contains("exp")) return "#it{CL} exp.";
    else if (varName.Contains("obs")) return "#it{CL} obs.";
    else return "#it{CL}";
  }
  else return varName;
}

/**
   -----------------------------------------------------------------------------
   Convert the DM sample name into a mediator mass.
   @param modeName - the name of the DM production mode.
   @returns - the mass of the mediator particle.
*/
int DMAnalysis::getMediatorMass(Config *config, TString modeName) {
  std::vector<double> massList = config->getNumV("DMMediatorMasses");
  for (int i_m = (int)massList.size()-1; i_m >= 0; i_m--) {
    if (modeName.Contains(Form("ms%d",((int)massList[i_m]))) ||
	modeName.Contains(Form("mzp%d",((int)massList[i_m])))) {
      return ((int)massList[i_m]);
    }
  }
  std::cout << "Analysis Error: no matching mediator mass "
	    << modeName << std::endl;
  exit(0);
}

/**
   -----------------------------------------------------------------------------
   Convert the DM sample name into a dark matter particle mass.
   @param modeName - the name of the DM production mode.
   @returns - the mass of the DM particle.
*/
int DMAnalysis::getDarkMatterMass(Config *config, TString modeName) {
  std::vector<double> massList = config->getNumV("DMParticleMasses");
  for (int i_m = (int)massList.size()-1; i_m >= 0; i_m--) {
    if (modeName.Contains(Form("mx%d",((int)massList[i_m]))) ||
	modeName.Contains(Form("mA%d",((int)massList[i_m])))) {
      return ((int)massList[i_m]);
    }
  }
  std::cout << "Analysis Error: no matching DM mass"
	    << modeName << std::endl;
  exit(0);
}

/**
   -----------------------------------------------------------------------------
   Check if the sample is among those listed as a background sample.
   @param config - The config file for the analysis settings.
   @param sampleName - The name of the sample being used.
   @returns - True iff the sample is a background sample.
*/
bool DMAnalysis::isBkgSample(Config *config, TString sampleName) {
  std::vector<TString> bkgProcesses = config->getStrV("BkgProcesses");
  for (int i_bkg = 0; i_bkg < (int)bkgProcesses.size(); i_bkg++) {
    if (sampleName.EqualTo(bkgProcesses[i_bkg])) return true;
  }
  return false;
}

/**
   -----------------------------------------------------------------------------
   Check if the sample is among those listed as a DM signal.
   @param config - The config file for the analysis settings.
   @param sampleName - The name of the sample being used.
   @returns - True iff the sample is a DM signal sample.
*/
bool DMAnalysis::isDMSample(Config *config, TString sampleName) {
  std::vector<TString> sigDMModes = config->getStrV("sigDMModes");
  for (int i_DM = 0; i_DM < (int)sigDMModes.size(); i_DM++) {
    if (sampleName.EqualTo(sigDMModes[i_DM])) return true;
  }
  return false;
}

/**
   -----------------------------------------------------------------------------
   Check if a sample is skimmed.
   @param config - The config file for the analysis settings.
   @param fileName - The name of the file.
   @returns - True iff the sample is skimmed.
*/
bool DMAnalysis::isSkimmed(Config *config, TString fileName) {
  std::vector<TString> skimmedTags = config->getStrV("TagSkimmed");
  std::vector<TString> unskimmedTags = config->getStrV("TagUnskimmed");

  for (int i_s = 0; i_s < (int)skimmedTags.size(); i_s++) {
    if (fileName.Contains(skimmedTags[i_s])) {
      std::cout << "DMAnalysis: Sample is skimmed." << std::endl;
      return true;
    }
  }

  for (int i_u = 0; i_u < (int)unskimmedTags.size(); i_u++) {
    if (fileName.Contains(unskimmedTags[i_u])) {
      std::cout << "DMAnalysis: Sample is unskimmed." << std::endl;
      return false;
    }
  }

  // Exit with error message if tag has not been identified:
  std::cout << "DMAnalysis: ERROR! Unidentified tag: " << fileName << std::endl;
  exit(0);
}

/**
   -----------------------------------------------------------------------------
   Check if the sample is among those listed as a SM signal.
   @param config - The config file for the analysis settings.
   @param sampleName - The name of the sample being used.
   @returns - True iff the sample is a SM signal sample.
*/
bool DMAnalysis::isSMSample(Config *config, TString sampleName) {
  std::vector<TString> sigSMModes = config->getStrV("sigSMModes");
  for (int i_SM = 0; i_SM < (int)sigSMModes.size(); i_SM++) {
    if (sampleName.EqualTo(sigSMModes[i_SM])) return true;
  }
  return false;
}

/**
   -----------------------------------------------------------------------------
   Check if the sample is among those listed as a DM or SM signal.
   @param config - The config file for the analysis settings.
   @param sampleName - The name of the sample being used.
   @returns - True iff the sample is a DM or SM signal sample.
*/
bool DMAnalysis::isSignalSample(Config *config, TString sampleName) {
  return (isSMSample(config, sampleName) || isDMSample(config, sampleName));
}

/**
   -----------------------------------------------------------------------------
   Check whether a sample should be weighted.
   @param config - The config file for the analysis settings.
   @param sampleName - The name of the sample being used.
   @returns - True iff the sample has associated event weights.
*/
bool DMAnalysis::isWeightedSample(Config *config, TString sampleName) {
  // First check if it is a SM or DM signal process:
  if (isDMSample(config, sampleName) || isSMSample(config, sampleName)) {
    return true;
  }

  // Finally, check if it is one of the other MC processes:
  std::vector<TString> BkgProcesses = config->getStrV("BkgProcesses");
  for (int i_b = 0; i_b < (int)BkgProcesses.size(); i_b++) {
    if (sampleName.EqualTo(BkgProcesses[i_b])) return true;
  }
  return false;
}

/**
   -----------------------------------------------------------------------------
    Convert the sample name to the corresponding file list.
    @param config - The config file for the analysis settings.
    @param name - The name of the sample.
    @returns - The file list location.
*/
TString DMAnalysis::nameToFileList(Config *config, TString name) {
  // Create a new file list:
  TString newListName = Form("%s/FileLists/list_%s.txt",
			     (config->getStr("masterInput")).Data(),
			     name.Data());
  std::ofstream newFileList(newListName);

  // Use a format specifier for DM samples:
  if (isDMSample(config, name)) {
    TString MxAODName = config->getStr("MxAODForm_DM");
    MxAODName = MxAODName.ReplaceAll("NAME",name);
    newFileList << config->getStr("MxAODDirectoryMC") << "/" << MxAODName
		<< std::endl;
  }
  // Use MxAOD list in the settings file for SM Higgs, backgrounds, and data:
  else {
    std::vector<TString> listMxAODs
      = config->getStrV(Form("MxAODList_%s", name.Data()));
    // loop over lines in the file, each of which is one contributing MxAOD:
    for (int i_m = 0; i_m < (int)listMxAODs.size(); i_m++) {
      TString directory = listMxAODs[i_m].Contains("data") ?
	config->getStr("MxAODDirectoryData") :
	config->getStr("MxAODDirectoryMC");
      newFileList << directory << "/" << listMxAODs[i_m] << std::endl;
    }
  }
  newFileList.close();
  return newListName;
}
<commit_msg>DMAnalysis creates file list dir<commit_after>////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//  Name: DMAnalysis.cxx                                                      //
//                                                                            //
//  Creator: Andrew Hard                                                      //
//  Email: ahard@cern.ch                                                      //
//  Date: 15/04/2015                                                          //
//                                                                            //
//  This namespace stores all of the global information for the H->gg + DM    //
//  search with 13 TeV data in 2015. It also has all of the includes that are //
//  necessary for the analysis.                                               //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

#include "DMAnalysis.h"

/**
   -----------------------------------------------------------------------------
   Convert the DM sample name into a process name, a subset of the full name.
   @param modeName - the name of the DM production mode.
   @param processName - the name of the process.
*/
TString DMAnalysis::getMediatorName(TString modeName) {
  if (modeName.Contains("shxx_gg")) return "shxx_gg";
  else if (modeName.Contains("zphxx_gg")) return "zphxx_gg";
  else if (modeName.Contains("zp2hdmxx_gg")) return "zp2hdmxx_gg";
  else {
    std::cout << "Analysis Error: no matching mediator name: "
	      << modeName << std::endl;
    exit(0);
  }
}

/**
   -----------------------------------------------------------------------------
   Convert the DM sample name into a process name, a subset of the full name.
   @param modeName - the name of the DM production mode.
   @param processName - the name of the process.
*/
TString DMAnalysis::getPrintMediatorName(TString modeName) {
  if (modeName.Contains("shxx_gg")) return "Scalar";
  else if (modeName.Contains("zphxx_gg")) return "Z'";
  else if (modeName.Contains("zp2hdmxx_gg")) return "Z_{2HDM}'";
  else {
    std::cout << "Analysis Error: no matching mediator name: "
	      << modeName << std::endl;
    exit(0);
  }
}

/**
   -----------------------------------------------------------------------------
   Get a pretty LaTex formatted name for a variable.
   @param sampleName - The name of the sample.
   @returns - A LaTex formatted TString.
*/
TString DMAnalysis::getPrintSampleName(Config *config, TString sampleName) {
  if (sampleName.EqualTo("gg")) return "#it{#gamma#gamma}";
  else if (sampleName.EqualTo("gjet")) return "#it{#gamma}+jet";
  else if (sampleName.EqualTo("SMHiggs")) {
    return "SM #it{H#rightarrow#gamma#gamma}";
  }
  else if (sampleName.EqualTo("yy")) return "#it{#gamma#gamma}";
  else if (sampleName.EqualTo("yjet")) return "#it{#gamma}+jet";
  else if (sampleName.EqualTo("jj")) return "di-jet";
  else if (sampleName.EqualTo("Zyy")) return "#it{Z#gamma#gamma}";
  else if (sampleName.EqualTo("Wyy")) return "#it{W#gamma#gamma}";
  else if (sampleName.EqualTo("Zy")) return "#it{Z#gamma}";
  else if (sampleName.EqualTo("Wy")) return "#it{W#gamma}";
  else if (sampleName.EqualTo("ttbar")) return "#it{t#bar{t}}";
  else if (sampleName.EqualTo("diboson")) return "#it{WW}+#it{WZ}+#it{ZZ}";
  else if (sampleName.EqualTo("ggH")) {
    return "#it{ggH(#rightarrow#gamma#gamma)}";
  }
  else if (sampleName.EqualTo("VBF")) {
    return "#it{VBF (H#rightarrow#gamma#gamma)}";
  }
  else if (sampleName.EqualTo("WH")) {
    return "#it{WH(#rightarrow#gamma#gamma)}";
  }
  else if (sampleName.EqualTo("ZH")) {
    return "#it{ZH(#rightarrow#gamma#gamma)}";
  }
  else if (sampleName.EqualTo("bbH")) {
    return "#it{b#bar{b}H(#rightarrow#gamma#gamma)}";
  }
  else if (sampleName.EqualTo("ttH")) {
    return "#it{t#bar{t}H(#rightarrow#gamma#gamma)}";
  }
  else if (DMAnalysis::isDMSample(config, sampleName)) {
    TString mediatorName = DMAnalysis::getMediatorName(sampleName);
    int mediatorMass = DMAnalysis::getMediatorMass(config, sampleName);
    TString medMassForm;
    if (mediatorName.EqualTo("shxx_gg")) {
      medMassForm = Form("#it{m_{S}}=%dGeV", mediatorMass);
    }
    else if (mediatorName.EqualTo("zphxx_gg")) {
      medMassForm = Form("#it{m_{Z'}}=%dGeV", mediatorMass);
    }
    else if (mediatorName.EqualTo("zp2hdmxx_gg")) {
      medMassForm = Form("#it{m_{Z'}}=%dGeV", mediatorMass);
    }

    int darkMatterMass = DMAnalysis::getDarkMatterMass(config, sampleName);
    TString darkMassForm;
    if (mediatorName.EqualTo("shxx_gg")) {
      darkMassForm = Form("#it{m_{#chi}}=%dGeV", darkMatterMass);
    }
    else if (mediatorName.EqualTo("zphxx_gg")) {
      darkMassForm = Form("#it{m_{#chi}}=%dGeV", darkMatterMass);
    }
    else if (mediatorName.EqualTo("zp2hdmxx_gg")) {
      darkMassForm = Form("#it{m_{A}}=%dGeV", darkMatterMass);
    }
    //(DMAnalysis::getPrintMediatorName(sampleName)).Data(),
    TString newName = Form("%s %s", medMassForm.Data(), darkMassForm.Data());
    return newName;
  }
  else return sampleName;
}

/**
   -----------------------------------------------------------------------------
   Get a pretty LaTex formatted name for a variable.
   @param varName - The name of the variable in the file.
   @returns - A LaTex formatted TString.
*/
TString DMAnalysis::getPrintVarName(TString varName) {
  varName.ToLower();
  varName = varName.ReplaceAll("anacut", "");
  if (varName.EqualTo("ptyy") || varName.EqualTo("diphotonpt")) {
    return "p_{T}^{#gamma#gamma} [GeV]";
  }
  else if (varName.EqualTo("etmiss")) return "#slash{E}_{T} [GeV]";
  else if (varName.EqualTo("ratioetmissptyy")) {
    return "#slash{E}_{T}/p_{T}^{#gamma#gamma}";
  }
  else if (varName.EqualTo("myy")) return "M_{#gamma#gamma} [GeV]";
  else if (varName.Contains("atanratio")) {
    return "tan^{-1}(#slash{E}_{T}/p_{T}^{#gamma#gamma})";
  }
  else if (varName.EqualTo("sumsqrtetmissptyy")) {
    return "#sqrt{(p_{T}^{#gamma#gamma})^{2} + (#slash{E}_{T})^{2}} [GeV]";
  }
  else if (varName.Contains("dphiyyetmiss")) {
    return "#Delta#phi(#gamma#gamma-#slash{E}_{T})";
  }
  else if (varName.Contains("njets")) return "N_{Jets}";
  else if (varName.Contains("nleptons")) return "N_{Leptons}";
  else if (varName.Contains("p0")) {
    if (varName.Contains("exp")) return "p_{0} exp.";
    else if (varName.Contains("obs")) return "p_{0} obs.";
    else return "p_{0}";
  }
  else if (varName.Contains("cl")) {
    if (varName.Contains("exp")) return "#it{CL} exp.";
    else if (varName.Contains("obs")) return "#it{CL} obs.";
    else return "#it{CL}";
  }
  else return varName;
}

/**
   -----------------------------------------------------------------------------
   Convert the DM sample name into a mediator mass.
   @param modeName - the name of the DM production mode.
   @returns - the mass of the mediator particle.
*/
int DMAnalysis::getMediatorMass(Config *config, TString modeName) {
  std::vector<double> massList = config->getNumV("DMMediatorMasses");
  for (int i_m = (int)massList.size()-1; i_m >= 0; i_m--) {
    if (modeName.Contains(Form("ms%d",((int)massList[i_m]))) ||
	modeName.Contains(Form("mzp%d",((int)massList[i_m])))) {
      return ((int)massList[i_m]);
    }
  }
  std::cout << "Analysis Error: no matching mediator mass "
	    << modeName << std::endl;
  exit(0);
}

/**
   -----------------------------------------------------------------------------
   Convert the DM sample name into a dark matter particle mass.
   @param modeName - the name of the DM production mode.
   @returns - the mass of the DM particle.
*/
int DMAnalysis::getDarkMatterMass(Config *config, TString modeName) {
  std::vector<double> massList = config->getNumV("DMParticleMasses");
  for (int i_m = (int)massList.size()-1; i_m >= 0; i_m--) {
    if (modeName.Contains(Form("mx%d",((int)massList[i_m]))) ||
	modeName.Contains(Form("mA%d",((int)massList[i_m])))) {
      return ((int)massList[i_m]);
    }
  }
  std::cout << "Analysis Error: no matching DM mass"
	    << modeName << std::endl;
  exit(0);
}

/**
   -----------------------------------------------------------------------------
   Check if the sample is among those listed as a background sample.
   @param config - The config file for the analysis settings.
   @param sampleName - The name of the sample being used.
   @returns - True iff the sample is a background sample.
*/
bool DMAnalysis::isBkgSample(Config *config, TString sampleName) {
  std::vector<TString> bkgProcesses = config->getStrV("BkgProcesses");
  for (int i_bkg = 0; i_bkg < (int)bkgProcesses.size(); i_bkg++) {
    if (sampleName.EqualTo(bkgProcesses[i_bkg])) return true;
  }
  return false;
}

/**
   -----------------------------------------------------------------------------
   Check if the sample is among those listed as a DM signal.
   @param config - The config file for the analysis settings.
   @param sampleName - The name of the sample being used.
   @returns - True iff the sample is a DM signal sample.
*/
bool DMAnalysis::isDMSample(Config *config, TString sampleName) {
  std::vector<TString> sigDMModes = config->getStrV("sigDMModes");
  for (int i_DM = 0; i_DM < (int)sigDMModes.size(); i_DM++) {
    if (sampleName.EqualTo(sigDMModes[i_DM])) return true;
  }
  return false;
}

/**
   -----------------------------------------------------------------------------
   Check if a sample is skimmed.
   @param config - The config file for the analysis settings.
   @param fileName - The name of the file.
   @returns - True iff the sample is skimmed.
*/
bool DMAnalysis::isSkimmed(Config *config, TString fileName) {
  std::vector<TString> skimmedTags = config->getStrV("TagSkimmed");
  std::vector<TString> unskimmedTags = config->getStrV("TagUnskimmed");

  for (int i_s = 0; i_s < (int)skimmedTags.size(); i_s++) {
    if (fileName.Contains(skimmedTags[i_s])) {
      std::cout << "DMAnalysis: Sample is skimmed." << std::endl;
      return true;
    }
  }

  for (int i_u = 0; i_u < (int)unskimmedTags.size(); i_u++) {
    if (fileName.Contains(unskimmedTags[i_u])) {
      std::cout << "DMAnalysis: Sample is unskimmed." << std::endl;
      return false;
    }
  }

  // Exit with error message if tag has not been identified:
  std::cout << "DMAnalysis: ERROR! Unidentified tag: " << fileName << std::endl;
  exit(0);
}

/**
   -----------------------------------------------------------------------------
   Check if the sample is among those listed as a SM signal.
   @param config - The config file for the analysis settings.
   @param sampleName - The name of the sample being used.
   @returns - True iff the sample is a SM signal sample.
*/
bool DMAnalysis::isSMSample(Config *config, TString sampleName) {
  std::vector<TString> sigSMModes = config->getStrV("sigSMModes");
  for (int i_SM = 0; i_SM < (int)sigSMModes.size(); i_SM++) {
    if (sampleName.EqualTo(sigSMModes[i_SM])) return true;
  }
  return false;
}

/**
   -----------------------------------------------------------------------------
   Check if the sample is among those listed as a DM or SM signal.
   @param config - The config file for the analysis settings.
   @param sampleName - The name of the sample being used.
   @returns - True iff the sample is a DM or SM signal sample.
*/
bool DMAnalysis::isSignalSample(Config *config, TString sampleName) {
  return (isSMSample(config, sampleName) || isDMSample(config, sampleName));
}

/**
   -----------------------------------------------------------------------------
   Check whether a sample should be weighted.
   @param config - The config file for the analysis settings.
   @param sampleName - The name of the sample being used.
   @returns - True iff the sample has associated event weights.
*/
bool DMAnalysis::isWeightedSample(Config *config, TString sampleName) {
  // First check if it is a SM or DM signal process:
  if (isDMSample(config, sampleName) || isSMSample(config, sampleName)) {
    return true;
  }

  // Finally, check if it is one of the other MC processes:
  std::vector<TString> BkgProcesses = config->getStrV("BkgProcesses");
  for (int i_b = 0; i_b < (int)BkgProcesses.size(); i_b++) {
    if (sampleName.EqualTo(BkgProcesses[i_b])) return true;
  }
  return false;
}

/**
   -----------------------------------------------------------------------------
    Convert the sample name to the corresponding file list.
    @param config - The config file for the analysis settings.
    @param name - The name of the sample.
    @returns - The file list location.
*/
TString DMAnalysis::nameToFileList(Config *config, TString name) {
  // Check that directory exists for file lists:
  system(Form("mkdir -vp %s/FileLists",(config->getStr("masterInput")).Data()));
  // Create a new file list:
  TString newListName = Form("%s/FileLists/list_%s.txt",
			     (config->getStr("masterInput")).Data(),
			     name.Data());
  std::ofstream newFileList(newListName);

  // Use a format specifier for DM samples:
  if (isDMSample(config, name)) {
    TString MxAODName = config->getStr("MxAODForm_DM");
    MxAODName = MxAODName.ReplaceAll("NAME",name);
    newFileList << config->getStr("MxAODDirectoryMC") << "/" << MxAODName
		<< std::endl;
  }
  // Use MxAOD list in the settings file for SM Higgs, backgrounds, and data:
  else {
    std::vector<TString> listMxAODs
      = config->getStrV(Form("MxAODList_%s", name.Data()));
    // loop over lines in the file, each of which is one contributing MxAOD:
    for (int i_m = 0; i_m < (int)listMxAODs.size(); i_m++) {
      TString directory = listMxAODs[i_m].Contains("data") ?
	config->getStr("MxAODDirectoryData") :
	config->getStr("MxAODDirectoryMC");
      newFileList << directory << "/" << listMxAODs[i_m] << std::endl;
    }
  }
  newFileList.close();
  return newListName;
}
<|endoftext|>


<commit_before>#include "pch.h"
#include "DspLimiter.h"

namespace SaneAudioRenderer
{
    namespace
    {
        const float slope = 1.0f - 1.0f / 20.0f; // 20:1 ratio

        template <typename T>
        T GetPeak(const T* data, size_t n)
        {
            T peak = 0;

            for (size_t i = 0; i < n; i++)
                peak = std::max(peak, std::abs(data[i]));

            return peak;
        }

        template <typename T>
        void ApplyLimiter(T* data, size_t n, T threshold)
        {
            for (size_t i = 0; i < n; i++)
            {
                T& sample = data[i];
                const T absSample = std::abs(sample);

                if (absSample > threshold)
                    sample *= std::pow(threshold / absSample, slope);

                assert(std::abs(sample) <= 1);
            }
        }
    }

    void DspLimiter::Initialize(uint32_t rate, uint32_t channels, bool exclusive)
    {
        m_exclusive = exclusive;
        m_rate = rate;
        m_channels = channels;

        m_active = false;
        m_holdWindow = 0;
        m_peak = 0.0f;
        m_threshold = 0.0f;
    }

    bool DspLimiter::Active()
    {
        return m_active;
    }

    void DspLimiter::Process(DspChunk& chunk)
    {
        if (chunk.IsEmpty())
            return;

        if (!m_exclusive || (chunk.GetFormat() != DspFormat::Float &&
                             chunk.GetFormat() != DspFormat::Double))
        {
            m_active = false;
            return;
        }

        m_active = true;

        // Analyze samples
        float peak;
        if (chunk.GetFormat() == DspFormat::Double)
        {
            double largePeak = GetPeak((double*)chunk.GetData(), chunk.GetSampleCount());
            peak = std::nexttoward((float)largePeak, largePeak);
        }
        else
        {
            assert(chunk.GetFormat() == DspFormat::Float);
            peak = GetPeak((float*)chunk.GetData(), chunk.GetSampleCount());
        }

        // Configure limiter
        if (peak > 1.0f)
        {
            if (m_holdWindow <= 0)
            {
                NewTreshold(std::max(peak, 1.4f));
            }
            else if (peak > m_peak)
            {
                NewTreshold(peak);
            }

            m_holdWindow = m_rate * m_channels * 10; // 10 seconds
        }

        // Apply limiter
        if (m_holdWindow > 0)
        {
            if (chunk.GetFormat() == DspFormat::Double)
            {
                ApplyLimiter<double>((double*)chunk.GetData(), chunk.GetSampleCount(), m_threshold);
            }
            else
            {
                assert(chunk.GetFormat() == DspFormat::Float);
                ApplyLimiter((float*)chunk.GetData(), chunk.GetSampleCount(), m_threshold);
            }

            m_holdWindow -= chunk.GetSampleCount();
        }
    }

    void DspLimiter::Finish(DspChunk& chunk)
    {
        Process(chunk);
    }

    void DspLimiter::NewTreshold(float peak)
    {
        m_peak = peak;
        m_threshold = std::pow(1.0f / peak, 1.0f / slope - 1.0f) - 0.0001f;
        DebugOut("DspLimiter active with", m_peak, "peak and", m_threshold, "threshold");
    }
}
<commit_msg>Fix coverity scan warning<commit_after>#include "pch.h"
#include "DspLimiter.h"

namespace SaneAudioRenderer
{
    namespace
    {
        const float slope = 1.0f - 1.0f / 20.0f; // 20:1 ratio

        template <typename T>
        T GetPeak(const T* data, size_t n)
        {
            T peak = 0;

            for (size_t i = 0; i < n; i++)
                peak = std::max(peak, std::abs(data[i]));

            return peak;
        }

        template <typename T>
        void ApplyLimiter(T* data, size_t n, T threshold)
        {
            for (size_t i = 0; i < n; i++)
            {
                T& sample = data[i];
                const T absSample = std::abs(sample);

                if (absSample > threshold)
                    sample *= std::pow(threshold / absSample, slope);

                assert(std::abs(sample) <= 1);
            }
        }
    }

    void DspLimiter::Initialize(uint32_t rate, uint32_t channels, bool exclusive)
    {
        m_exclusive = exclusive;
        m_rate = rate;
        m_channels = channels;

        m_active = false;
        m_holdWindow = 0;
        m_peak = 0.0f;
        m_threshold = 0.0f;
    }

    bool DspLimiter::Active()
    {
        return m_active;
    }

    void DspLimiter::Process(DspChunk& chunk)
    {
        if (chunk.IsEmpty())
            return;

        if (!m_exclusive || (chunk.GetFormat() != DspFormat::Float &&
                             chunk.GetFormat() != DspFormat::Double))
        {
            m_active = false;
            return;
        }

        m_active = true;

        // Analyze samples
        float peak;
        if (chunk.GetFormat() == DspFormat::Double)
        {
            double largePeak = GetPeak((double*)chunk.GetData(), chunk.GetSampleCount());
            peak = std::nexttoward((float)largePeak, largePeak);
        }
        else
        {
            assert(chunk.GetFormat() == DspFormat::Float);
            peak = GetPeak((float*)chunk.GetData(), chunk.GetSampleCount());
        }

        // Configure limiter
        if (peak > 1.0f)
        {
            if (m_holdWindow <= 0)
            {
                NewTreshold(std::max(peak, 1.4f));
            }
            else if (peak > m_peak)
            {
                NewTreshold(peak);
            }

            m_holdWindow = (int64_t)m_rate * m_channels * 10; // 10 seconds
        }

        // Apply limiter
        if (m_holdWindow > 0)
        {
            if (chunk.GetFormat() == DspFormat::Double)
            {
                ApplyLimiter<double>((double*)chunk.GetData(), chunk.GetSampleCount(), m_threshold);
            }
            else
            {
                assert(chunk.GetFormat() == DspFormat::Float);
                ApplyLimiter((float*)chunk.GetData(), chunk.GetSampleCount(), m_threshold);
            }

            m_holdWindow -= chunk.GetSampleCount();
        }
    }

    void DspLimiter::Finish(DspChunk& chunk)
    {
        Process(chunk);
    }

    void DspLimiter::NewTreshold(float peak)
    {
        m_peak = peak;
        m_threshold = std::pow(1.0f / peak, 1.0f / slope - 1.0f) - 0.0001f;
        DebugOut("DspLimiter active with", m_peak, "peak and", m_threshold, "threshold");
    }
}
<|endoftext|>


<commit_before>#include "Game/Clock.h"

#include <array>
#include <chrono>
using namespace std::chrono_literals;
#include <cassert>
#include <limits>

#include "Game/Board.h"
#include "Game/Game_Result.h"

Clock::Clock(seconds duration_seconds,
             size_t moves_to_reset,
             seconds increment_seconds,
             Time_Reset_Method reset_method,
             Piece_Color starting_turn,
             std::chrono::system_clock::time_point previous_start_time) noexcept :
    timers({duration_seconds, duration_seconds}),
    initial_start_time(duration_seconds),
    increment_time({increment_seconds, increment_seconds}),
    move_count_reset(moves_to_reset),
    method_of_reset(reset_method),
    whose_turn(starting_turn),
    game_start_date_time(previous_start_time)
{
}

Game_Result Clock::punch(const Board& board) noexcept
{
    assert(clocks_running);

    if( ! is_in_use())
    {
        return {};
    }

    auto time_this_punch = std::chrono::steady_clock::now();

    auto player_index = static_cast<unsigned>(whose_turn);
    timers[player_index] -= (time_this_punch - time_previous_punch);

    if(++moves_to_reset_clocks[player_index] == move_count_reset)
    {
        if(method_of_reset == Time_Reset_Method::ADDITION)
        {
            timers[player_index] += initial_start_time;
        }
        else
        {
            timers[player_index] = initial_start_time;
        }
        moves_to_reset_clocks[player_index] = 0;
    }

    time_previous_punch = time_this_punch;
    timers[player_index] += increment_time[player_index];

    whose_turn = opposite(whose_turn);

    if(time_left(opposite(whose_turn)) < 0s)
    {
        if(board.enough_material_to_checkmate(whose_turn))
        {
            return Game_Result(whose_turn, Game_Result_Type::TIME_FORFEIT);
        }
        else
        {
            return Game_Result(Winner_Color::NONE, Game_Result_Type::TIME_EXPIRED_WITH_INSUFFICIENT_MATERIAL);
        }
    }
    else
    {
        return {};
    }
}

void Clock::unpunch() noexcept
{
    moves_to_reset_clocks[static_cast<unsigned>(whose_turn)] -= 1;
    moves_to_reset_clocks[static_cast<unsigned>(opposite(whose_turn))] -= 1;
    punch({});
}

void Clock::stop() noexcept
{
    auto time_stop = std::chrono::steady_clock::now();
    timers[static_cast<unsigned>(whose_turn)] -= (time_stop - time_previous_punch);
    clocks_running = false;
}

void Clock::start() noexcept
{
    static const auto default_game_start_date_time = std::chrono::system_clock::time_point{};
    time_previous_punch = std::chrono::steady_clock::now();
    if(game_start_date_time == default_game_start_date_time)
    {
        game_start_date_time = std::chrono::system_clock::now();
    }
    clocks_running = true;
}

Clock::seconds Clock::time_left(Piece_Color color) const noexcept
{
    if( ! is_in_use())
    {
        return 0s;
    }

    if(whose_turn != color || ! clocks_running)
    {
        return timers[static_cast<unsigned>(color)];
    }
    else
    {
        auto now = std::chrono::steady_clock::now();
        return timers[static_cast<unsigned>(color)] - (now - time_previous_punch);
    }
}

size_t Clock::moves_until_reset(Piece_Color color) const noexcept
{
    if(move_count_reset > 0)
    {
        return move_count_reset - moves_to_reset_clocks[static_cast<unsigned>(color)];
    }
    else
    {
        return std::numeric_limits<int>::max();
    }
}

Piece_Color Clock::running_for() const noexcept
{
    return whose_turn;
}

void Clock::set_time(Piece_Color player, seconds new_time_seconds) noexcept
{
    timers[static_cast<unsigned>(player)] = new_time_seconds;

    // This function is called by GUI mediators, so the actual
    // start time will be during one of the first two calls
    // (first if the local player is white, second if black).
    if(++initial_time_set_count <= 2)
    {
        initial_start_time = std::max(new_time_seconds, initial_start_time);
    }
    time_previous_punch = std::chrono::steady_clock::now();
}

void Clock::set_increment(Piece_Color player, seconds new_increment_time_seconds) noexcept
{
    increment_time[static_cast<unsigned>(player)] = new_increment_time_seconds;
}

void Clock::set_next_time_reset(size_t moves_to_reset) noexcept
{
    if(moves_to_reset == 0)
    {
        move_count_reset = 0;
    }
    else
    {
        move_count_reset = moves_to_reset_clocks[static_cast<unsigned>(running_for())] + moves_to_reset;
    }
}

void Clock::set_reset_method(Time_Reset_Method method) noexcept
{
    method_of_reset = method;
}

Clock::seconds Clock::running_time_left() const noexcept
{
    return time_left(running_for());
}

bool Clock::is_running() const noexcept
{
    return clocks_running;
}

std::chrono::system_clock::time_point Clock::game_start_date_and_time() const noexcept
{
    return game_start_date_time;
}

size_t Clock::moves_per_time_period() const noexcept
{
    return move_count_reset;
}

Time_Reset_Method Clock::reset_mode() const noexcept
{
    return method_of_reset;
}

Clock::seconds Clock::initial_time() const noexcept
{
    return initial_start_time;
}

Clock::seconds Clock::increment(Piece_Color color) const noexcept
{
    return increment_time[static_cast<unsigned>(color)];
}

bool Clock::is_in_use() const noexcept
{
    return initial_start_time > 0s;
}
<commit_msg>Time only added to clock if time left after move<commit_after>#include "Game/Clock.h"

#include <array>
#include <chrono>
using namespace std::chrono_literals;
#include <cassert>
#include <limits>

#include "Game/Board.h"
#include "Game/Game_Result.h"

Clock::Clock(seconds duration_seconds,
             size_t moves_to_reset,
             seconds increment_seconds,
             Time_Reset_Method reset_method,
             Piece_Color starting_turn,
             std::chrono::system_clock::time_point previous_start_time) noexcept :
    timers({duration_seconds, duration_seconds}),
    initial_start_time(duration_seconds),
    increment_time({increment_seconds, increment_seconds}),
    move_count_reset(moves_to_reset),
    method_of_reset(reset_method),
    whose_turn(starting_turn),
    game_start_date_time(previous_start_time)
{
}

Game_Result Clock::punch(const Board& board) noexcept
{
    assert(clocks_running);

    if( ! is_in_use())
    {
        return {};
    }

    auto time_this_punch = std::chrono::steady_clock::now();

    auto player_index = static_cast<unsigned>(whose_turn);
    timers[player_index] -= (time_this_punch - time_previous_punch);
    time_previous_punch = time_this_punch;
    whose_turn = opposite(whose_turn);

    if(time_left(opposite(whose_turn)) < 0s)
    {
        if(board.enough_material_to_checkmate(whose_turn))
        {
            return Game_Result(whose_turn, Game_Result_Type::TIME_FORFEIT);
        }
        else
        {
            return Game_Result(Winner_Color::NONE, Game_Result_Type::TIME_EXPIRED_WITH_INSUFFICIENT_MATERIAL);
        }
    }
    else
    {
        if(++moves_to_reset_clocks[player_index] == move_count_reset)
        {
            if(method_of_reset == Time_Reset_Method::ADDITION)
            {
                timers[player_index] += initial_start_time;
            }
            else
            {
                timers[player_index] = initial_start_time;
            }
            moves_to_reset_clocks[player_index] = 0;
        }
        timers[player_index] += increment_time[player_index];

        return {};
    }
}

void Clock::unpunch() noexcept
{
    moves_to_reset_clocks[static_cast<unsigned>(whose_turn)] -= 1;
    moves_to_reset_clocks[static_cast<unsigned>(opposite(whose_turn))] -= 1;
    punch({});
}

void Clock::stop() noexcept
{
    auto time_stop = std::chrono::steady_clock::now();
    timers[static_cast<unsigned>(whose_turn)] -= (time_stop - time_previous_punch);
    clocks_running = false;
}

void Clock::start() noexcept
{
    static const auto default_game_start_date_time = std::chrono::system_clock::time_point{};
    time_previous_punch = std::chrono::steady_clock::now();
    if(game_start_date_time == default_game_start_date_time)
    {
        game_start_date_time = std::chrono::system_clock::now();
    }
    clocks_running = true;
}

Clock::seconds Clock::time_left(Piece_Color color) const noexcept
{
    if( ! is_in_use())
    {
        return 0s;
    }

    if(whose_turn != color || ! clocks_running)
    {
        return timers[static_cast<unsigned>(color)];
    }
    else
    {
        auto now = std::chrono::steady_clock::now();
        return timers[static_cast<unsigned>(color)] - (now - time_previous_punch);
    }
}

size_t Clock::moves_until_reset(Piece_Color color) const noexcept
{
    if(move_count_reset > 0)
    {
        return move_count_reset - moves_to_reset_clocks[static_cast<unsigned>(color)];
    }
    else
    {
        return std::numeric_limits<int>::max();
    }
}

Piece_Color Clock::running_for() const noexcept
{
    return whose_turn;
}

void Clock::set_time(Piece_Color player, seconds new_time_seconds) noexcept
{
    timers[static_cast<unsigned>(player)] = new_time_seconds;

    // This function is called by GUI mediators, so the actual
    // start time will be during one of the first two calls
    // (first if the local player is white, second if black).
    if(++initial_time_set_count <= 2)
    {
        initial_start_time = std::max(new_time_seconds, initial_start_time);
    }
    time_previous_punch = std::chrono::steady_clock::now();
}

void Clock::set_increment(Piece_Color player, seconds new_increment_time_seconds) noexcept
{
    increment_time[static_cast<unsigned>(player)] = new_increment_time_seconds;
}

void Clock::set_next_time_reset(size_t moves_to_reset) noexcept
{
    if(moves_to_reset == 0)
    {
        move_count_reset = 0;
    }
    else
    {
        move_count_reset = moves_to_reset_clocks[static_cast<unsigned>(running_for())] + moves_to_reset;
    }
}

void Clock::set_reset_method(Time_Reset_Method method) noexcept
{
    method_of_reset = method;
}

Clock::seconds Clock::running_time_left() const noexcept
{
    return time_left(running_for());
}

bool Clock::is_running() const noexcept
{
    return clocks_running;
}

std::chrono::system_clock::time_point Clock::game_start_date_and_time() const noexcept
{
    return game_start_date_time;
}

size_t Clock::moves_per_time_period() const noexcept
{
    return move_count_reset;
}

Time_Reset_Method Clock::reset_mode() const noexcept
{
    return method_of_reset;
}

Clock::seconds Clock::initial_time() const noexcept
{
    return initial_start_time;
}

Clock::seconds Clock::increment(Piece_Color color) const noexcept
{
    return increment_time[static_cast<unsigned>(color)];
}

bool Clock::is_in_use() const noexcept
{
    return initial_start_time > 0s;
}
<|endoftext|>


<commit_before>/*!
 * IpcChannel.cpp
 *
 *  Created on: Feb 6, 2015
 *      Author: Tim Nicholls, STFC Application Engineering
 */

#include "IpcChannel.h"

using namespace FrameReceiver;

IpcContext& IpcContext::Instance(void)
{
    static IpcContext ipcContext;
    return ipcContext;
}

zmq::context_t& IpcContext::get(void)
{
    return zmq_context_;
}

IpcContext::IpcContext(int io_threads) :
    zmq_context_(io_threads)
{
    // std::cout << "IpcContext constructor" << std::endl;
}

IpcChannel::IpcChannel(int type) :
    context_(IpcContext::Instance()),
    socket_(context_.get(), type)
{
    //std::cout << "IpcChannel constructor" << std::endl;
}

IpcChannel::~IpcChannel()
{
    //td::cout << "IpcChannel destructor" << std::endl;
}

void IpcChannel::bind(const char* endpoint)
{
    socket_.bind(endpoint);
}

void IpcChannel::bind(std::string& endpoint)
{
    this->bind(endpoint.c_str());
}

void IpcChannel::connect(const char* endpoint)
{
    socket_.connect(endpoint);
}

void IpcChannel::connect(std::string& endpoint)
{
    this->connect(endpoint.c_str());
}

void IpcChannel::send(std::string& message_str)
{
    size_t msg_size = message_str.size() + 1;
    zmq::message_t msg(msg_size);
    memcpy(msg.data(), message_str.data(), msg_size);
    socket_.send(msg);
}

void IpcChannel::send(const char* message)
{
    size_t msg_size = strlen(message) + 1;
    zmq::message_t msg(msg_size);
    memcpy(msg.data(), message, msg_size);
    socket_.send(msg);

}

std::string IpcChannel::recv(void)
{
    zmq::message_t msg;
    socket_.recv(&msg);

    return std::string(reinterpret_cast<const char*>(msg.data()));
}

bool IpcChannel::poll(long timeout_ms)
{
    zmq::pollitem_t pollitems[] = {{socket_, 0, ZMQ_POLLIN, 0}};

    zmq::poll(pollitems, 1, timeout_ms);

    return (pollitems[0].revents & ZMQ_POLLIN);

}

<commit_msg>Fixed recv() method to convert message to string of appropriate size<commit_after>/*!
 * IpcChannel.cpp
 *
 *  Created on: Feb 6, 2015
 *      Author: Tim Nicholls, STFC Application Engineering
 */

#include "IpcChannel.h"

using namespace FrameReceiver;

IpcContext& IpcContext::Instance(void)
{
    static IpcContext ipcContext;
    return ipcContext;
}

zmq::context_t& IpcContext::get(void)
{
    return zmq_context_;
}

IpcContext::IpcContext(int io_threads) :
    zmq_context_(io_threads)
{
    // std::cout << "IpcContext constructor" << std::endl;
}

IpcChannel::IpcChannel(int type) :
    context_(IpcContext::Instance()),
    socket_(context_.get(), type)
{
    //std::cout << "IpcChannel constructor" << std::endl;
}

IpcChannel::~IpcChannel()
{
    //td::cout << "IpcChannel destructor" << std::endl;
}

void IpcChannel::bind(const char* endpoint)
{
    socket_.bind(endpoint);
}

void IpcChannel::bind(std::string& endpoint)
{
    this->bind(endpoint.c_str());
}

void IpcChannel::connect(const char* endpoint)
{
    socket_.connect(endpoint);
}

void IpcChannel::connect(std::string& endpoint)
{
    this->connect(endpoint.c_str());
}

void IpcChannel::send(std::string& message_str)
{
    size_t msg_size = message_str.size() + 1;
    zmq::message_t msg(msg_size);
    memcpy(msg.data(), message_str.data(), msg_size);
    socket_.send(msg);
}

void IpcChannel::send(const char* message)
{
    size_t msg_size = strlen(message) + 1;
    zmq::message_t msg(msg_size);
    memcpy(msg.data(), message, msg_size);
    socket_.send(msg);

}

std::string IpcChannel::recv(void)
{
    zmq::message_t msg;
    socket_.recv(&msg);

    return std::string(reinterpret_cast<const char*>(msg.data()), msg.size());
}

bool IpcChannel::poll(long timeout_ms)
{
    zmq::pollitem_t pollitems[] = {{socket_, 0, ZMQ_POLLIN, 0}};

    zmq::poll(pollitems, 1, timeout_ms);

    return (pollitems[0].revents & ZMQ_POLLIN);

}

<|endoftext|>


<commit_before>#include "MapManager.hpp"

#include <cstring>
#include <cstdio>

MapManager::MapManager(void) {
    unsigned int i, j;
    numLandmarks = 0;
    head = tail = NULL;
    for (i = 0; i < MAX_LMARKS; ++i)
        for (j = 0; j < MAX_LMARKS; ++j)
            weight[i][j] = 0;
}

MapManager::~MapManager(void) {
    destroyLandmarkList();
}

void MapManager::destroyLandmarkList(void) {
    landmarkStructType *x, *y = head;
    while (y != NULL) {
        x = y;
        y = y->next;
        delete x;
    }
}

int MapManager::insertLandmark(int index, char *name) {
    landmarkStructType *temp;

    // Is the name too long?
    if (strlen(name) > MAX_LMARK_NAME)
        return NAME_TOO_LONG;

    // Is the name repeated?
    for (temp = head; temp != NULL; temp = temp->next)
        if (strcmp(temp->name, name) == 0)
            return NAME_REPEATED;

    // Create a new index.
    temp = new landmarkStructType;
    temp->index = index;
    strcpy(temp->name, name);
    temp->next = NULL; // Always insert new nodes at the end.

    // Check if the linked list is empty.
    if (head == NULL) {
        // Linked list is empty.
        temp->prev = NULL;
        head = temp;
        tail = temp;
    } else {
        // No, insert new node at the tail.
        tail->next = temp;
        temp->prev = tail;
        tail = temp;
    }
    return SUCCESS;
}

char *MapManager::getLandmarkName(unsigned int index) {
    landmarkStructType *x;

    if ((index > numLandmarks) || (index < 0))
        return NULL;

    for (x = head; x != NULL; x = x->next)
        if (x->index == index)
            return x->name;

    return NULL; // Not found. something is wrong.
}

int MapManager::getLandmarkIndex(char *name) {
    landmarkStructType *x;
    if (strlen(name) > MAX_LMARK_NAME)
        return -1;

    for (x = head; x != NULL; x = x->next)
        if (strcmp(x->name, name) == 0)
            return x->index;

    return LMARK_UNDEFINED; // Not found. something is wrong.
}

int MapManager::readInputFile(char *fname) {
    FILE *f = NULL;
    char temp, name[MAX_LMARK_NAME];
    unsigned int i, j;

    if ((f = fopen(fname, "r")) == NULL) {
        cerr << "Could not open input file '" << fname << "'..." << endl;
        return FAILED_TO_OPEN_FILE;
    }

    // Read in the landmark list.
    fscanf(f, "%d", &numLandmarks);
    if ((numLandmarks <= 0) || (numLandmarks > MAX_LMARKS)) {
        cout << "Invalid number of landmarks: " << numLandmarks << endl;
        return INVALID_NUM_LMARKS;
    }

    // Read in the landmark names.
    for (i = 0; i < numLandmarks; ++i) {
        // Ignore all preceding blank spaces.
        do {
            fscanf(f, "%c", &temp);
        } while (isspace(temp));

        // Start taking in the name.
        for (j = 0; j < MAX_LMARK_NAME; ++j) {
            fscanf(f, "%c", &name[j]);
            if (name[j] == '"') {
                name[j] = '\0'; // End of name.
                break;
            }
        }

        // Insert a new node.
        if (insertLandmark(i, name) == NAME_REPEATED) {
            destroyLandmarkList();
            return NAME_REPEATED;
        }
    }

    // Read in the adjacency matrix giving the inter-landmark weights.
    for (i = 0; i < numLandmarks; ++i)
        for (j = 0; j < numLandmarks; ++j) {
            fscanf(f, "%d", &weight[i][j]);
            if (weight[i][j] < 0) {
                destroyLandmarkList();
                return INVALID_EDGE_WEIGHT;
            }
        }

    fclose(f);
    return SUCCESS;
}

void MapManager::setWeight(int row, int col, int value) {
    weight[row][col] = value;
}

int MapManager::getNumLandmarks(void) {
    return numLandmarks;
}

int MapManager::getWeight(int row, int col) {
    return weight[row][col];
}

void MapManager::print() {
    landmarkStructType *x;
    unsigned int i, j;

    cout << "Number of landmarks: " << numLandmarks << endl;
    cout << "List of landmarks: " << endl;
    for (x = head; x != NULL; x = x->next)
        cout << "    " << x->name << endl;
    cout << "Inter-landmark weights: " << endl;
    for (i = 0; i < numLandmarks; ++i) {
        for (j = 0; j < numLandmarks; ++j)
            cout << weight[i][j] << " ";
        cout << endl;
    }
}<commit_msg>Renamed constant.<commit_after>#include "MapManager.hpp"

#include <cstring>
#include <cstdio>

MapManager::MapManager(void) {
    unsigned int i, j;
    numLandmarks = 0;
    head = tail = NULL;
    for (i = 0; i < MAX_LMARKS; ++i)
        for (j = 0; j < MAX_LMARKS; ++j)
            weight[i][j] = 0;
}

MapManager::~MapManager(void) {
    destroyLandmarkList();
}

void MapManager::destroyLandmarkList(void) {
    landmarkStructType *x, *y = head;
    while (y != NULL) {
        x = y;
        y = y->next;
        delete x;
    }
}

int MapManager::insertLandmark(int index, char *name) {
    landmarkStructType *temp;

    // Is the name too long?
    if (strlen(name) > MAX_LMARK_NAME)
        return NAME_TOO_LONG;

    // Is the name repeated?
    for (temp = head; temp != NULL; temp = temp->next)
        if (strcmp(temp->name, name) == 0)
            return NAME_REPEATED;

    // Create a new index.
    temp = new landmarkStructType;
    temp->index = index;
    strcpy(temp->name, name);
    temp->next = NULL; // Always insert new nodes at the end.

    // Check if the linked list is empty.
    if (head == NULL) {
        // Linked list is empty.
        temp->prev = NULL;
        head = temp;
        tail = temp;
    } else {
        // No, insert new node at the tail.
        tail->next = temp;
        temp->prev = tail;
        tail = temp;
    }
    return SUCCESS;
}

char *MapManager::getLandmarkName(unsigned int index) {
    landmarkStructType *x;

    if ((index > numLandmarks) || (index < 0))
        return NULL;

    for (x = head; x != NULL; x = x->next)
        if (x->index == index)
            return x->name;

    return NULL; // Not found. something is wrong.
}

int MapManager::getLandmarkIndex(char *name) {
    landmarkStructType *x;
    if (strlen(name) > MAX_LMARK_NAME)
        return -1;

    for (x = head; x != NULL; x = x->next)
        if (strcmp(x->name, name) == 0)
            return x->index;

    return UNDEFINED_LMARK; // Not found. something is wrong.
}

int MapManager::readInputFile(char *fname) {
    FILE *f = NULL;
    char temp, name[MAX_LMARK_NAME];
    unsigned int i, j;

    if ((f = fopen(fname, "r")) == NULL) {
        cerr << "Could not open input file '" << fname << "'..." << endl;
        return FAILED_TO_OPEN_FILE;
    }

    // Read in the landmark list.
    fscanf(f, "%d", &numLandmarks);
    if ((numLandmarks <= 0) || (numLandmarks > MAX_LMARKS)) {
        cout << "Invalid number of landmarks: " << numLandmarks << endl;
        return INVALID_NUM_LMARKS;
    }

    // Read in the landmark names.
    for (i = 0; i < numLandmarks; ++i) {
        // Ignore all preceding blank spaces.
        do {
            fscanf(f, "%c", &temp);
        } while (isspace(temp));

        // Start taking in the name.
        for (j = 0; j < MAX_LMARK_NAME; ++j) {
            fscanf(f, "%c", &name[j]);
            if (name[j] == '"') {
                name[j] = '\0'; // End of name.
                break;
            }
        }

        // Insert a new node.
        if (insertLandmark(i, name) == NAME_REPEATED) {
            destroyLandmarkList();
            return NAME_REPEATED;
        }
    }

    // Read in the adjacency matrix giving the inter-landmark weights.
    for (i = 0; i < numLandmarks; ++i)
        for (j = 0; j < numLandmarks; ++j) {
            fscanf(f, "%d", &weight[i][j]);
            if (weight[i][j] < 0) {
                destroyLandmarkList();
                return INVALID_EDGE_WEIGHT;
            }
        }

    fclose(f);
    return SUCCESS;
}

void MapManager::setWeight(int row, int col, int value) {
    weight[row][col] = value;
}

int MapManager::getNumLandmarks(void) {
    return numLandmarks;
}

int MapManager::getWeight(int row, int col) {
    return weight[row][col];
}

void MapManager::print() {
    landmarkStructType *x;
    unsigned int i, j;

    cout << "Number of landmarks: " << numLandmarks << endl;
    cout << "List of landmarks: " << endl;
    for (x = head; x != NULL; x = x->next)
        cout << "    " << x->name << endl;
    cout << "Inter-landmark weights: " << endl;
    for (i = 0; i < numLandmarks; ++i) {
        for (j = 0; j < numLandmarks; ++j)
            cout << weight[i][j] << " ";
        cout << endl;
    }
}<|endoftext|>


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

#include <sensor_msgs/PointCloud2.h>
#include <pcl/ros/conversions.h>
#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
#include <pcl/common/transforms.h>
#include <cmath>

using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;

void
printHelp (int, char **argv)
{
  print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
  print_info ("  where options are:\n");
  print_info ("           -trans dx,dy,dz           = the translation (default: ");
  print_value ("%0.1f, %0.1f, %0.1f", 0, 0, 0); print_info (")\n");
  print_info ("           -quat w,x,y,z             = rotation as quaternion\n");
  print_info ("           -axisangle ax,ay,az,theta = rotation in axis-angle form\n");
  print_info ("           -scale x,y,z              = scale each dimension with these values\n");
  print_info ("           -matrix v1,v2,...,v8,v9   = a 3x3 affine transform\n");
  print_info ("           -matrix v1,v2,...,v15,v16 = a 4x4 transformation matrix\n");
  print_info ("   Note: If a rotation is not specified, it will default to no rotation.\n");
  print_info ("         If redundant or conflicting transforms are specified, then:\n");
  print_info ("           -axisangle will override -quat\n");
  print_info ("           -matrix (3x3) will take override -axisangle and -quat\n");
  print_info ("           -matrix (4x4) will take override all other arguments\n");

}

void
printElapsedTimeAndNumberOfPoints (double t, int w, int h = 1)
{
  print_info ("[done, "); print_value ("%g", t); print_info (" ms : ");
  print_value ("%d", w*h); print_info (" points]\n");
}

bool
loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)
{
  TicToc tt;
  print_highlight ("Loading "); print_value ("%s ", filename.c_str ());

  tt.tic ();
  if (loadPCDFile (filename, cloud) < 0)
    return (false);

  printElapsedTimeAndNumberOfPoints (tt.toc (), cloud.width, cloud.height);

  print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());

  return (true);
}

template <typename PointT> void
transformPointCloudHelper (PointCloud<PointT> & input, PointCloud<PointT> & output,
                           Eigen::Matrix4f &tform)
{
  transformPointCloud (input, output, tform);
}

template <> void
transformPointCloudHelper (PointCloud<PointNormal> & input, PointCloud<PointNormal> & output,
                           Eigen::Matrix4f &tform)
{
  transformPointCloudWithNormals (input, output, tform);
}

template <> void
transformPointCloudHelper<PointXYZRGBNormal> (PointCloud<PointXYZRGBNormal> & input,
                                              PointCloud<PointXYZRGBNormal> & output,
                                              Eigen::Matrix4f &tform)
{
  transformPointCloudWithNormals (input, output, tform);
}

template <typename PointT> void
transformPointCloud2AsType (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output,
                            Eigen::Matrix4f &tform)
{
  PointCloud<PointT> cloud;
  fromROSMsg (input, cloud);
  transformPointCloudHelper (cloud, cloud, tform);
  toROSMsg (cloud, output);
}

void
transformPointCloud2 (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output,
                      Eigen::Matrix4f &tform)
{
  // Check for 'rgb' and 'normals' fields
  bool has_rgb = false;
  bool has_normals = false;
  for (size_t i = 0; i < input.fields.size (); ++i)
  {
    if (input.fields[i].name == "rgb")
      has_rgb = true;
    if (input.fields[i].name == "normals")
      has_normals = true;
  }

  // Handle the following four point types differently: PointXYZ, PointXYZRGB, PointNormal, PointXYZRGBNormal
  if (!has_rgb && !has_normals)
    transformPointCloud2AsType<PointXYZ> (input, output, tform);
  else if (has_rgb && !has_normals)
    transformPointCloud2AsType<PointXYZRGB> (input, output, tform);
  else if (!has_rgb && has_normals)
    transformPointCloud2AsType<PointNormal> (input, output, tform);
  else // (has_rgb && has_normals)
    transformPointCloud2AsType<PointXYZRGBNormal> (input, output, tform);
}

void
compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,
         Eigen::Matrix4f &tform)
{
  TicToc tt;
  tt.tic ();

  print_highlight ("Transforming ");

  transformPointCloud2 (*input, output, tform);

  printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height);
}

void
saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)
{
  TicToc tt;
  tt.tic ();

  print_highlight ("Saving "); print_value ("%s ", filename.c_str ());

  pcl::io::savePCDFile (filename, output);

  printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height);
}

template <typename T> void
divide (sensor_msgs::PointCloud2 &cloud, int field_offset, double divider)
{
  T val;
  memcpy (&val, &cloud.data[field_offset], sizeof (T));
  val /= T (divider);
  memcpy (&cloud.data[field_offset], &val, sizeof (T));
}

void
scaleInPlace (sensor_msgs::PointCloud2 &cloud, double* divider)
{
  // Obtain the x, y, and z indices
  int x_idx = pcl::getFieldIndex (cloud, "x");
  int y_idx = pcl::getFieldIndex (cloud, "y");
  int z_idx = pcl::getFieldIndex (cloud, "z");
  Eigen::Array3i xyz_offset (cloud.fields[x_idx].offset, cloud.fields[y_idx].offset, cloud.fields[z_idx].offset);

  for (uint32_t cp = 0; cp < cloud.width * cloud.height; ++cp)
  {
    assert (cloud.fields[x_idx].datatype == cloud.fields[y_idx].datatype == cloud.fields[z_idx].datatype);  // Assume all 3 fields are the same (XYZ)
    switch (cloud.fields[x_idx].datatype)
    {
      case sensor_msgs::PointField::INT8:
        for (int i = 0; i < 3; ++i) divide<int8_t> (cloud, xyz_offset[i], divider[i]);
        break;
      case sensor_msgs::PointField::UINT8:
        for (int i = 0; i < 3; ++i) divide<uint8_t> (cloud, xyz_offset[i], divider[i]);
        break;
      case sensor_msgs::PointField::INT16:
        for (int i = 0; i < 3; ++i) divide<int16_t> (cloud, xyz_offset[i], divider[i]);
        break;
      case sensor_msgs::PointField::UINT16:
        for (int i = 0; i < 3; ++i) divide<uint16_t> (cloud, xyz_offset[i], divider[i]);
        break;
      case sensor_msgs::PointField::INT32:
        for (int i = 0; i < 3; ++i) divide<int32_t> (cloud, xyz_offset[i], divider[i]);
        break;
      case sensor_msgs::PointField::UINT32:
        for (int i = 0; i < 3; ++i) divide<uint32_t> (cloud, xyz_offset[i], divider[i]);
        break;
      case sensor_msgs::PointField::FLOAT32:
        for (int i = 0; i < 3; ++i) divide<float> (cloud, xyz_offset[i], divider[i]);
        break;
      case sensor_msgs::PointField::FLOAT64:
        for (int i = 0; i < 3; ++i) divide<double> (cloud, xyz_offset[i], divider[i]);
        break;
    }
    xyz_offset += cloud.point_step;
  }
}

/* ---[ */
int
main (int argc, char** argv)
{
  print_info ("Transform a cloud. For more information, use: %s -h\n", argv[0]);

  bool help = false;
  parse_argument (argc, argv, "-h", help);
  if (argc < 3 || help)
  {
    printHelp (argc, argv);
    return (-1);
  }

  // Parse the command line arguments for .pcd files
  std::vector<int> p_file_indices;
  p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
  if (p_file_indices.size () != 2)
  {
    print_error ("Need one input PCD file and one output PCD file to continue.\n");
    return (-1);
  }

  // Initialize the transformation matrix
  Eigen::Matrix4f tform;
  tform.setIdentity ();

  // Command line parsing
  float dx, dy, dz;
  std::vector<float> values;

  if (parse_3x_arguments (argc, argv, "-trans", dx, dy, dz) > -1)
  {
    tform (0, 3) = dx;
    tform (1, 3) = dy;
    tform (2, 3) = dz;
  }

  if (parse_x_arguments (argc, argv, "-quat", values) > -1)
  {
    if (values.size () == 4)
    {
      const float& x = values[0];
      const float& y = values[1];
      const float& z = values[2];
      const float& w = values[3];
      tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::Quaternionf (w, x, y, z));
    }
    else
    {
      print_error ("Wrong number of values given (%zu): ", values.size ());
      print_error ("The quaternion specified with -quat must contain 4 elements (w,x,y,z).\n");
    }
  }

  if (parse_x_arguments (argc, argv, "-axisangle", values) > -1)
  {
    if (values.size () == 4)
    {
      const float& ax = values[0];
      const float& ay = values[1];
      const float& az = values[2];
      const float& theta = values[3];
      tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::AngleAxisf (theta, Eigen::Vector3f (ax, ay, az)));
    }
    else
    {
      print_error ("Wrong number of values given (%zu): ", values.size ());
      print_error ("The rotation specified with -axisangle must contain 4 elements (ax,ay,az,theta).\n");
    }
  }

  if (parse_x_arguments (argc, argv, "-matrix", values) > -1)
  {
    if (values.size () == 9 || values.size () == 16)
    {
      int n = values.size () == 9 ? 3 : 4;
      for (int r = 0; r < n; ++r)
        for (int c = 0; c < n; ++c)
          tform (r, c) = values[n*r+c];
    }
    else
    {
      print_error ("Wrong number of values given (%zu): ", values.size ());
      print_error ("The transformation specified with -matrix must be 3x3 (9) or 4x4 (16).\n");
    }
  }

  // Load the first file
  sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);
  if (!loadCloud (argv[p_file_indices[0]], *cloud))
    return (-1);

  // Apply the transform
  sensor_msgs::PointCloud2 output;
  compute (cloud, output, tform);

  // Check if a scaling parameter has been given
  double divider[3];
  if (parse_3x_arguments (argc, argv, "-scale", divider[0], divider[1], divider[2]) > -1)
  {
    print_highlight ("Scaling XYZ data with the following values: %f, %f, %f\n", divider[0], divider[1], divider[2]);
    scaleInPlace (output, divider);
  }

  // Save into the second file
  saveCloud (argv[p_file_indices[1]], output);
}

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

#include <sensor_msgs/PointCloud2.h>
#include <pcl/ros/conversions.h>
#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
#include <pcl/common/transforms.h>
#include <cmath>

using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;

void
printHelp (int, char **argv)
{
  print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
  print_info ("  where options are:\n");
  print_info ("           -trans dx,dy,dz           = the translation (default: ");
  print_value ("%0.1f, %0.1f, %0.1f", 0, 0, 0); print_info (")\n");
  print_info ("           -quat w,x,y,z             = rotation as quaternion\n");
  print_info ("           -axisangle ax,ay,az,theta = rotation in axis-angle form\n");
  print_info ("           -scale x,y,z              = scale each dimension with these values\n");
  print_info ("           -matrix v1,v2,...,v8,v9   = a 3x3 affine transform\n");
  print_info ("           -matrix v1,v2,...,v15,v16 = a 4x4 transformation matrix\n");
  print_info ("   Note: If a rotation is not specified, it will default to no rotation.\n");
  print_info ("         If redundant or conflicting transforms are specified, then:\n");
  print_info ("           -axisangle will override -quat\n");
  print_info ("           -matrix (3x3) will take override -axisangle and -quat\n");
  print_info ("           -matrix (4x4) will take override all other arguments\n");

}

void
printElapsedTimeAndNumberOfPoints (double t, int w, int h = 1)
{
  print_info ("[done, "); print_value ("%g", t); print_info (" ms : ");
  print_value ("%d", w*h); print_info (" points]\n");
}

bool
loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)
{
  TicToc tt;
  print_highlight ("Loading "); print_value ("%s ", filename.c_str ());

  tt.tic ();
  if (loadPCDFile (filename, cloud) < 0)
    return (false);

  printElapsedTimeAndNumberOfPoints (tt.toc (), cloud.width, cloud.height);

  print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());

  return (true);
}

template <typename PointT> void
transformPointCloudHelper (PointCloud<PointT> & input, PointCloud<PointT> & output,
                           Eigen::Matrix4f &tform)
{
  transformPointCloud (input, output, tform);
}

template <> void
transformPointCloudHelper (PointCloud<PointNormal> & input, PointCloud<PointNormal> & output,
                           Eigen::Matrix4f &tform)
{
  transformPointCloudWithNormals (input, output, tform);
}

template <> void
transformPointCloudHelper<PointXYZRGBNormal> (PointCloud<PointXYZRGBNormal> & input,
                                              PointCloud<PointXYZRGBNormal> & output,
                                              Eigen::Matrix4f &tform)
{
  transformPointCloudWithNormals (input, output, tform);
}

template <typename PointT> void
transformPointCloud2AsType (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output,
                            Eigen::Matrix4f &tform)
{
  PointCloud<PointT> cloud;
  fromROSMsg (input, cloud);
  transformPointCloudHelper (cloud, cloud, tform);
  toROSMsg (cloud, output);
}

void
transformPointCloud2 (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output,
                      Eigen::Matrix4f &tform)
{
  // Check for 'rgb' and 'normals' fields
  bool has_rgb = false;
  bool has_normals = false;
  for (size_t i = 0; i < input.fields.size (); ++i)
  {
    if (input.fields[i].name == "rgb")
      has_rgb = true;
    if (input.fields[i].name == "normals")
      has_normals = true;
  }

  // Handle the following four point types differently: PointXYZ, PointXYZRGB, PointNormal, PointXYZRGBNormal
  if (!has_rgb && !has_normals)
    transformPointCloud2AsType<PointXYZ> (input, output, tform);
  else if (has_rgb && !has_normals)
    transformPointCloud2AsType<PointXYZRGB> (input, output, tform);
  else if (!has_rgb && has_normals)
    transformPointCloud2AsType<PointNormal> (input, output, tform);
  else // (has_rgb && has_normals)
    transformPointCloud2AsType<PointXYZRGBNormal> (input, output, tform);
}

void
compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,
         Eigen::Matrix4f &tform)
{
  TicToc tt;
  tt.tic ();

  print_highlight ("Transforming ");

  transformPointCloud2 (*input, output, tform);

  printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height);
}

void
saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)
{
  TicToc tt;
  tt.tic ();

  print_highlight ("Saving "); print_value ("%s ", filename.c_str ());

  pcl::io::savePCDFile (filename, output);

  printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height);
}

template <typename T> void
divide (sensor_msgs::PointCloud2 &cloud, int field_offset, double divider)
{
  T val;
  memcpy (&val, &cloud.data[field_offset], sizeof (T));
  val /= T (divider);
  memcpy (&cloud.data[field_offset], &val, sizeof (T));
}

void
scaleInPlace (sensor_msgs::PointCloud2 &cloud, double* divider)
{
  // Obtain the x, y, and z indices
  int x_idx = pcl::getFieldIndex (cloud, "x");
  int y_idx = pcl::getFieldIndex (cloud, "y");
  int z_idx = pcl::getFieldIndex (cloud, "z");
  Eigen::Array3i xyz_offset (cloud.fields[x_idx].offset, cloud.fields[y_idx].offset, cloud.fields[z_idx].offset);

  for (uint32_t cp = 0; cp < cloud.width * cloud.height; ++cp)
  {
    // Assume all 3 fields are the same (XYZ)
    assert ((cloud.fields[x_idx].datatype == cloud.fields[y_idx].datatype));
    assert ((cloud.fields[x_idx].datatype == cloud.fields[z_idx].datatype));
    switch (cloud.fields[x_idx].datatype)
    {
      case sensor_msgs::PointField::INT8:
        for (int i = 0; i < 3; ++i) divide<int8_t> (cloud, xyz_offset[i], divider[i]);
        break;
      case sensor_msgs::PointField::UINT8:
        for (int i = 0; i < 3; ++i) divide<uint8_t> (cloud, xyz_offset[i], divider[i]);
        break;
      case sensor_msgs::PointField::INT16:
        for (int i = 0; i < 3; ++i) divide<int16_t> (cloud, xyz_offset[i], divider[i]);
        break;
      case sensor_msgs::PointField::UINT16:
        for (int i = 0; i < 3; ++i) divide<uint16_t> (cloud, xyz_offset[i], divider[i]);
        break;
      case sensor_msgs::PointField::INT32:
        for (int i = 0; i < 3; ++i) divide<int32_t> (cloud, xyz_offset[i], divider[i]);
        break;
      case sensor_msgs::PointField::UINT32:
        for (int i = 0; i < 3; ++i) divide<uint32_t> (cloud, xyz_offset[i], divider[i]);
        break;
      case sensor_msgs::PointField::FLOAT32:
        for (int i = 0; i < 3; ++i) divide<float> (cloud, xyz_offset[i], divider[i]);
        break;
      case sensor_msgs::PointField::FLOAT64:
        for (int i = 0; i < 3; ++i) divide<double> (cloud, xyz_offset[i], divider[i]);
        break;
    }
    xyz_offset += cloud.point_step;
  }
}

/* ---[ */
int
main (int argc, char** argv)
{
  print_info ("Transform a cloud. For more information, use: %s -h\n", argv[0]);

  bool help = false;
  parse_argument (argc, argv, "-h", help);
  if (argc < 3 || help)
  {
    printHelp (argc, argv);
    return (-1);
  }

  // Parse the command line arguments for .pcd files
  std::vector<int> p_file_indices;
  p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
  if (p_file_indices.size () != 2)
  {
    print_error ("Need one input PCD file and one output PCD file to continue.\n");
    return (-1);
  }

  // Initialize the transformation matrix
  Eigen::Matrix4f tform;
  tform.setIdentity ();

  // Command line parsing
  float dx, dy, dz;
  std::vector<float> values;

  if (parse_3x_arguments (argc, argv, "-trans", dx, dy, dz) > -1)
  {
    tform (0, 3) = dx;
    tform (1, 3) = dy;
    tform (2, 3) = dz;
  }

  if (parse_x_arguments (argc, argv, "-quat", values) > -1)
  {
    if (values.size () == 4)
    {
      const float& x = values[0];
      const float& y = values[1];
      const float& z = values[2];
      const float& w = values[3];
      tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::Quaternionf (w, x, y, z));
    }
    else
    {
      print_error ("Wrong number of values given (%zu): ", values.size ());
      print_error ("The quaternion specified with -quat must contain 4 elements (w,x,y,z).\n");
    }
  }

  if (parse_x_arguments (argc, argv, "-axisangle", values) > -1)
  {
    if (values.size () == 4)
    {
      const float& ax = values[0];
      const float& ay = values[1];
      const float& az = values[2];
      const float& theta = values[3];
      tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::AngleAxisf (theta, Eigen::Vector3f (ax, ay, az)));
    }
    else
    {
      print_error ("Wrong number of values given (%zu): ", values.size ());
      print_error ("The rotation specified with -axisangle must contain 4 elements (ax,ay,az,theta).\n");
    }
  }

  if (parse_x_arguments (argc, argv, "-matrix", values) > -1)
  {
    if (values.size () == 9 || values.size () == 16)
    {
      int n = values.size () == 9 ? 3 : 4;
      for (int r = 0; r < n; ++r)
        for (int c = 0; c < n; ++c)
          tform (r, c) = values[n*r+c];
    }
    else
    {
      print_error ("Wrong number of values given (%zu): ", values.size ());
      print_error ("The transformation specified with -matrix must be 3x3 (9) or 4x4 (16).\n");
    }
  }

  // Load the first file
  sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);
  if (!loadCloud (argv[p_file_indices[0]], *cloud))
    return (-1);

  // Apply the transform
  sensor_msgs::PointCloud2 output;
  compute (cloud, output, tform);

  // Check if a scaling parameter has been given
  double divider[3];
  if (parse_3x_arguments (argc, argv, "-scale", divider[0], divider[1], divider[2]) > -1)
  {
    print_highlight ("Scaling XYZ data with the following values: %f, %f, %f\n", divider[0], divider[1], divider[2]);
    scaleInPlace (output, divider);
  }

  // Save into the second file
  saveCloud (argv[p_file_indices[1]], output);
}

<|endoftext|>


<commit_before>/*
    Copyright (C) 2010  Collabora Multimedia.
      @author Mauricio Piacentini <mauricio.piacentini@collabora.co.uk>

    This library is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published
    by the Free Software Foundation; either version 2.1 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "clock.h"

#include <QtCore/QTime>
#include <gst/gstclock.h>
#include <gst/gstsystemclock.h>

namespace QGst {

ClockPtr Clock::systemClock()
{
    return ClockPtr::wrap(gst_system_clock_obtain(), false);
}

ClockTime Clock::clockTime() const
{
    GstClockTime t = gst_clock_get_time(object<GstClock>());
    return t;
}

ClockTime Clock::resolution() const
{
    GstClockTime t = gst_clock_get_resolution(object<GstClock>());
    return t;
}

QTime Clock::time() const
{
    return clockTime().toTime();
}

}
<commit_msg>src/QGst/clock.cpp add #include <glib-object.h>, <gst/gstconfig.h><commit_after>/*
    Copyright (C) 2010  Collabora Multimedia.
      @author Mauricio Piacentini <mauricio.piacentini@collabora.co.uk>

    This library is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published
    by the Free Software Foundation; either version 2.1 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "clock.h"

#include <QtCore/QTime>
#include <glib-object.h>
#include <gst/gstconfig.h>
#include <gst/gstclock.h>
#include <gst/gstsystemclock.h>

namespace QGst {

ClockPtr Clock::systemClock()
{
    return ClockPtr::wrap(gst_system_clock_obtain(), false);
}

ClockTime Clock::clockTime() const
{
    GstClockTime t = gst_clock_get_time(object<GstClock>());
    return t;
}

ClockTime Clock::resolution() const
{
    GstClockTime t = gst_clock_get_resolution(object<GstClock>());
    return t;
}

QTime Clock::time() const
{
    return clockTime().toTime();
}

}
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <errno.h>
#include <QApplication>
#include <QFrame>
#include <QTextCodec>

#include "../typedef.h"
#include "../config.h"
#include "../console.h"
#include "../error.h"
#include "../osd.h"
#include "../pc60.h"

//SDLMainとのコンフリクト解消
#undef main

#ifdef SDL_VIDEO_DRIVER_X11
#include <X11/Xlib.h>
#endif
///////////////////////////////////////////////////////////
// メイン
///////////////////////////////////////////////////////////
int main( int argc, char *argv[] )
{
#ifdef SDL_VIDEO_DRIVER_X11
    //X11環境でSDLスレッドを使用するために必要。
    XInitThreads();
#endif

    VM6 *P6Core             = NULL;			// オブジェクトポインタ
    VM6::ReturnCode Restart = VM6::Quit;	// 再起動フラグ
    cConfig *Cfg            = NULL;			// 環境設定オブジェクト

    QApplication app(argc, argv);
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));

    setlocale(LC_ALL,"Japanese");

    // 環境変数設定(テスト用)
    //	putenv( "SDL_VIDEODRIVER=windib" );
    //	putenv( "SDL_VIDEODRIVER=directx" );
    //	putenv( "SDL_AUDIODRIVER=dsound" );

    // 二重起動禁止
    if( OSD_IsWorking() ) return FALSE;

    // 設定ファイルフォルダを作成
    if( !OSD_CreateConfigPath() ) return FALSE;

    // SDL初期化
    if( SDL_Init( SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK ) < 0 ){
        Error::SetError( Error::LibInitFailed );
        OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONERROR );
        OSD_Finish();	// 終了処理
        return FALSE;
    }

    // INIファイル読込み
    Cfg = new cConfig();
    if( !Cfg ){
        SDL_Quit();		// SDLシャットダウン
        OSD_Finish();	// 終了処理
    }
    if( !Cfg->Init() ){
        switch( Error::GetError() ){
        case Error::IniDefault:
            OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONWARNING );
            Error::SetError( Error::NoError );
            break;

        default:
            OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONERROR );
            SDL_Quit();				// SDLシャットダウン
            OSD_Finish();			// 終了処理
            if( Cfg ) delete Cfg;	// 環境設定オブジェクト開放
            return FALSE;
        }
    }

    // フォントファイルが無ければ作成する
    if( !OSD_FileExist( Cfg->GetFontFileH() ) ) OSD_CreateFont( Cfg->GetFontFileH(), NULL, FSIZE );
    if( !OSD_FileExist( Cfg->GetFontFileZ() ) ) OSD_CreateFont( NULL, Cfg->GetFontFileZ(), FSIZE );

    // P6オブジェクトを作成して実行
    do{
        Restart = VM6::Quit;

        // ROMファイル存在チェック&機種変更
        char RomSerch[PATH_MAX];
        int IniModel = Cfg->GetModel();
        sprintf( RomSerch, "%s*.%2d", Cfg->GetRomPath(), IniModel );
        if( !OSD_FileExist( RomSerch ) ){
            int models[] = { 60, 62, 66 };
            for( int i=0; i < COUNTOF(models); i++ ){
                sprintf( RomSerch, "%s*.%2d", Cfg->GetRomPath(), models[i] );
                if( OSD_FileExist( RomSerch ) ){
                    Cfg->SetModel( models[i] );
                    break;
                }
            }
            // ROMある?
            if( IniModel != Cfg->GetModel() ){
                Error::SetError( Error::RomChange );
                OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONWARNING );
                Error::SetError( Error::NoError );
            }
        }

        // 機種別P6オブジェクト確保
        const char* iconRes = NULL;
        switch( Cfg->GetModel() ){
        case 62: P6Core = new VM62; iconRes = ":/res/PC-6001mk2.ico"; break;
        case 66: P6Core = new VM66; iconRes = ":/res/PC-6601.ico"; break;
        default: P6Core = new VM60; iconRes = ":/res/PC-6001.ico";
        }

        // アイコン設定
        QImage icon = QImage(iconRes).convertToFormat(QImage::Format_RGB16);
        SDL_Surface *p6icon = SDL_CreateRGBSurfaceFrom( icon.bits(), icon.width(), icon.height(), icon.depth(), icon.bytesPerLine(), 0, 0, 0, 0 );
        SDL_WM_SetIcon( p6icon, icon.alphaChannel().bits() );
        SDL_FreeSurface( p6icon );

        // VMを初期化して実行
        if( P6Core->Init( Cfg ) ){
            switch( Restart ){
            case VM6::Doko:		// どこでもLOAD?
                P6Core->DokoDemoLoad( Cfg->GetDokoFile() );
                break;

            case VM6::Replay:	// リプレイ再生?
            {
                char temp[PATH_MAX];
                strncpy( temp, Cfg->GetDokoFile(), PATH_MAX );
                P6Core->DokoDemoLoad( temp );
                P6Core->REPLAY::StartReplay( temp );
            }
            break;

            default:
                break;
            }

            P6Core->Start();
            Restart = P6Core->EventLoop();
            P6Core->Stop();
        }else{
            // 失敗した場合
            OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONERROR );
        }

        // P6オブジェクトを開放
        if( P6Core ) delete P6Core;

        // 再起動ならばINIファイル再読込み
        if( Restart == VM6::Restart ){
            if( !Cfg->Init() ){
                Error::SetError( Error::IniDefault );
                OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONWARNING );
                Error::SetError( Error::NoError );
            }
        }

    }while( Restart != VM6::Quit );

    // 環境設定オブジェクト開放
    if( Cfg ) delete Cfg;

    // SDLシャットダウン
    SDL_Quit();

    // 終了処理
    OSD_Finish();

    return TRUE;
}
<commit_msg>Fixed crash when QtSDK is not installed due to lack of qjpcodec4.dll.<commit_after>#include <stdlib.h>
#include <errno.h>
#include <QApplication>
#include <QFrame>
#include <QTextCodec>

#include "../typedef.h"
#include "../config.h"
#include "../console.h"
#include "../error.h"
#include "../osd.h"
#include "../pc60.h"

//SDLMainとのコンフリクト解消
#undef main

#ifdef SDL_VIDEO_DRIVER_X11
#include <X11/Xlib.h>
#endif
///////////////////////////////////////////////////////////
// メイン
///////////////////////////////////////////////////////////
int main( int argc, char *argv[] )
{
#ifdef SDL_VIDEO_DRIVER_X11
    //X11環境でSDLスレッドを使用するために必要。
    XInitThreads();
#endif

    VM6 *P6Core             = NULL;			// オブジェクトポインタ
    VM6::ReturnCode Restart = VM6::Quit;	// 再起動フラグ
    cConfig *Cfg            = NULL;			// 環境設定オブジェクト

    QApplication app(argc, argv);
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));

    setlocale(LC_ALL,"Japanese");

#ifdef WIN32
    // Windowsではアプリに同梱のqjpcodecs4.dllプラグインを読み込むため、そのパスを指定
    QApplication::addLibraryPath(qApp->applicationFilePath());
#endif

    // 環境変数設定(テスト用)
    //	putenv( "SDL_VIDEODRIVER=windib" );
    //	putenv( "SDL_VIDEODRIVER=directx" );
    //	putenv( "SDL_AUDIODRIVER=dsound" );

    // 二重起動禁止
    if( OSD_IsWorking() ) return FALSE;

    // 設定ファイルフォルダを作成
    if( !OSD_CreateConfigPath() ) return FALSE;

    // SDL初期化
    if( SDL_Init( SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK ) < 0 ){
        Error::SetError( Error::LibInitFailed );
        OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONERROR );
        OSD_Finish();	// 終了処理
        return FALSE;
    }

    // INIファイル読込み
    Cfg = new cConfig();
    if( !Cfg ){
        SDL_Quit();		// SDLシャットダウン
        OSD_Finish();	// 終了処理
    }
    if( !Cfg->Init() ){
        switch( Error::GetError() ){
        case Error::IniDefault:
            OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONWARNING );
            Error::SetError( Error::NoError );
            break;

        default:
            OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONERROR );
            SDL_Quit();				// SDLシャットダウン
            OSD_Finish();			// 終了処理
            if( Cfg ) delete Cfg;	// 環境設定オブジェクト開放
            return FALSE;
        }
    }

    // フォントファイルが無ければ作成する
    if( !OSD_FileExist( Cfg->GetFontFileH() ) ) OSD_CreateFont( Cfg->GetFontFileH(), NULL, FSIZE );
    if( !OSD_FileExist( Cfg->GetFontFileZ() ) ) OSD_CreateFont( NULL, Cfg->GetFontFileZ(), FSIZE );

    // P6オブジェクトを作成して実行
    do{
        Restart = VM6::Quit;

        // ROMファイル存在チェック&機種変更
        char RomSerch[PATH_MAX];
        int IniModel = Cfg->GetModel();
        sprintf( RomSerch, "%s*.%2d", Cfg->GetRomPath(), IniModel );
        if( !OSD_FileExist( RomSerch ) ){
            int models[] = { 60, 62, 66 };
            for( int i=0; i < COUNTOF(models); i++ ){
                sprintf( RomSerch, "%s*.%2d", Cfg->GetRomPath(), models[i] );
                if( OSD_FileExist( RomSerch ) ){
                    Cfg->SetModel( models[i] );
                    break;
                }
            }
            // ROMある?
            if( IniModel != Cfg->GetModel() ){
                Error::SetError( Error::RomChange );
                OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONWARNING );
                Error::SetError( Error::NoError );
            }
        }

        // 機種別P6オブジェクト確保
        const char* iconRes = NULL;
        switch( Cfg->GetModel() ){
        case 62: P6Core = new VM62; iconRes = ":/res/PC-6001mk2.ico"; break;
        case 66: P6Core = new VM66; iconRes = ":/res/PC-6601.ico"; break;
        default: P6Core = new VM60; iconRes = ":/res/PC-6001.ico";
        }

        // アイコン設定
        QImage icon = QImage(iconRes).convertToFormat(QImage::Format_RGB16);
        SDL_Surface *p6icon = SDL_CreateRGBSurfaceFrom( icon.bits(), icon.width(), icon.height(), icon.depth(), icon.bytesPerLine(), 0, 0, 0, 0 );
        SDL_WM_SetIcon( p6icon, icon.alphaChannel().bits() );
        SDL_FreeSurface( p6icon );

        // VMを初期化して実行
        if( P6Core->Init( Cfg ) ){
            switch( Restart ){
            case VM6::Doko:		// どこでもLOAD?
                P6Core->DokoDemoLoad( Cfg->GetDokoFile() );
                break;

            case VM6::Replay:	// リプレイ再生?
            {
                char temp[PATH_MAX];
                strncpy( temp, Cfg->GetDokoFile(), PATH_MAX );
                P6Core->DokoDemoLoad( temp );
                P6Core->REPLAY::StartReplay( temp );
            }
            break;

            default:
                break;
            }

            P6Core->Start();
            Restart = P6Core->EventLoop();
            P6Core->Stop();
        }else{
            // 失敗した場合
            OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONERROR );
        }

        // P6オブジェクトを開放
        if( P6Core ) delete P6Core;

        // 再起動ならばINIファイル再読込み
        if( Restart == VM6::Restart ){
            if( !Cfg->Init() ){
                Error::SetError( Error::IniDefault );
                OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONWARNING );
                Error::SetError( Error::NoError );
            }
        }

    }while( Restart != VM6::Quit );

    // 環境設定オブジェクト開放
    if( Cfg ) delete Cfg;

    // SDLシャットダウン
    SDL_Quit();

    // 終了処理
    OSD_Finish();

    return TRUE;
}
<|endoftext|>