<commit_before>AliAnalysisTask *AddTask_dsekihat_lowmass_PbPb(
    Bool_t getFromAlien = kFALSE,
    TString cFileName = "Config_dsekihat_lowmass_PbPb.C",
    TString lFileName = "LMEECutLib_dsekihat.C",
		TString calibFileName = "",
    UInt_t trigger = AliVEvent::kINT7|AliVEvent::kCentral|AliVEvent::kSemiCentral,
    const Int_t CenMin =  0,
    const Int_t CenMax = 10,
    const Int_t Nmix   = 10,
    const Float_t PtMin = 0.2,
    const Float_t PtMax = 10,
    const Float_t EtaMin = -0.8,
    const Float_t EtaMax = +0.8
    )
{
  //get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTask_dsekihat_lowmass_PbPb", "No analysis manager found.");
    return 0;
  }

  //Base Directory for GRID / LEGO Train
  TString configBasePath= "$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/";
  //TString configBasePath= "./";
  if(getFromAlien
    && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/macrosLMEE/%s .",cFileName.Data())))
    && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/macrosLMEE/%s .",lFileName.Data())))
    ){
    configBasePath=Form("%s/",gSystem->pwd());
  }

  TString configFilePath(configBasePath + cFileName);
  TString libFilePath(configBasePath + lFileName);
  std::cout << "Configpath:  " << configFilePath << std::endl;
  std::cout << "Libpath:  "    << libFilePath << std::endl;

  TString triggername = "NULL";
  if(trigger == (UInt_t)AliVEvent::kINT7)             triggername = "kINT7";
  else if(trigger == (UInt_t)AliVEvent::kCentral)     triggername = "kCentral";
  else if(trigger == (UInt_t)AliVEvent::kSemiCentral) triggername = "kSemiCentral";
  else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral | AliVEvent::kSemiCentral)) triggername = "kCombinedCentralityTriggers";

  //create task and add it to the manager (MB)
  AliAnalysisTaskMultiDielectron *task = new AliAnalysisTaskMultiDielectron(Form("MultiDielectron_Cen%d_%d_%s",CenMin,CenMax,triggername.Data()));
  task->UsePhysicsSelection(kTRUE);
  task->SetTriggerMask(trigger);

  //add dielectron analysis with different cuts to the task
  gROOT->LoadMacro(libFilePath.Data());//library first
  gROOT->LoadMacro(configFilePath.Data());

  //const Int_t nDie = (Int_t)gROOT->ProcessLine("GetN()");
  const Int_t nTC  = Int_t(gROOT->ProcessLine("GetNTC()") );
  const Int_t nPID = Int_t(gROOT->ProcessLine("GetNPID()"));
  const Int_t nPF  = Int_t(gROOT->ProcessLine("GetNPF()") );

  THnF *hs_mean_TPC_El  = 0x0;
  THnF *hs_width_TPC_El = 0x0;
  THnF *hs_mean_ITS_El  = 0x0;
  THnF *hs_width_ITS_El = 0x0;
  THnF *hs_mean_TOF_El  = 0x0;
  THnF *hs_width_TOF_El = 0x0;
  THnF *hs_mean_TPC_Pi  = 0x0;
  THnF *hs_width_TPC_Pi = 0x0;

	TFile *rootfile = 0x0;
	if(calibFileName != ""){
		printf("reading : %s for PID calibration\n",calibFileName.Data());
		rootfile = TFile::Open(calibFileName,"READ");
		hs_mean_TPC_El  = (THnF*)rootfile->Get("hs_mean_TPC_El");
		hs_width_TPC_El = (THnF*)rootfile->Get("hs_width_TPC_El");
		hs_mean_ITS_El  = (THnF*)rootfile->Get("hs_mean_ITS_El");
		hs_width_ITS_El = (THnF*)rootfile->Get("hs_width_ITS_El");
		hs_mean_TOF_El  = (THnF*)rootfile->Get("hs_mean_TOF_El");
		hs_width_TOF_El = (THnF*)rootfile->Get("hs_width_TOF_El");
		hs_mean_TPC_Pi  = (THnF*)rootfile->Get("hs_mean_TPC_Pi");
		hs_width_TPC_Pi = (THnF*)rootfile->Get("hs_width_TPC_Pi");
	}

  for (Int_t itc=0; itc<nTC; ++itc){
    for (Int_t ipid=0; ipid<nPID; ++ipid){
      for (Int_t ipf=0; ipf<nPF; ++ipf){
        AliDielectron *diel = reinterpret_cast<AliDielectron*>(gROOT->ProcessLine(Form("Config_dsekihat_lowmass_PbPb(%d,%d,%d,%f,%f,%f,%f)",itc,ipid,ipf,PtMin,PtMax,EtaMin,EtaMax)));
        if(!diel) continue;

        //AliDielectronVarCuts*  centCuts = new AliDielectronVarCuts("centCuts",Form("kPbPb%02d%02d",CenMin,CenMax));
        //centCuts->AddCut(AliDielectronVarManager::kCentralityNew, (Float_t)CenMin, (Float_t)CenMax);
        //diel->GetEventFilter().AddCuts(centCuts);

				//if(calibFileName!=""){
				if(rootfile && rootfile->IsOpen()){
					diel->SetPIDCaibinPU(kTRUE);
					//for electron
					diel->SetCentroidCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kElectron,hs_mean_TPC_El ,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM);
					diel->   SetWidthCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kElectron,hs_width_TPC_El,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM);
					diel->SetCentroidCorrFunctionPU(AliDielectronPID::kITS,AliPID::kElectron,hs_mean_ITS_El ,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM);
					diel->   SetWidthCorrFunctionPU(AliDielectronPID::kITS,AliPID::kElectron,hs_width_ITS_El,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM);
					diel->SetCentroidCorrFunctionPU(AliDielectronPID::kTOF,AliPID::kElectron,hs_mean_TOF_El ,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM);
					diel->   SetWidthCorrFunctionPU(AliDielectronPID::kTOF,AliPID::kElectron,hs_width_TOF_El,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM);
					//for pion
					diel->SetCentroidCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kPion,hs_mean_TPC_Pi ,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM);
					diel->   SetWidthCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kPion,hs_width_TPC_Pi ,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM);
				}

        TString name = diel->GetName();
        if(name.Contains("PIDCalib",TString::kIgnoreCase) || name.Contains("noPID",TString::kIgnoreCase)){
          printf("No event mixing handler for post PID calibration/noPID\n");
        }
        else{
          printf("Add event mixing handler\n");
          AliDielectronMixingHandler *mix = new AliDielectronMixingHandler;
          mix->SetMixType(AliDielectronMixingHandler::kAll);
          mix->AddVariable(AliDielectronVarManager::kZvPrim,"-10., -8., -6., -4., -2. , 0., 2., 4., 6., 8. , 10.");
          mix->AddVariable(AliDielectronVarManager::kCentralityNew,"0,5,10,30,50,70,90,101");
          mix->AddVariable(AliDielectronVarManager::kNacc,"0,10000");
          mix->SetDepth(Nmix);
          diel->SetMixingHandler(mix);
        }
        task->AddDielectron(diel);
      }//pre-filter loop
    }//PID loop
  }//track cut loop

	//if(rootfile && rootfile->IsOpen()) rootfile->Close();

  task->SetEventFilter(reinterpret_cast<AliDielectronEventCuts*>(gROOT->ProcessLine(Form("LMEECutLib::SetupEventCuts(%f,%f,%d,\"%s\")",(Float_t)CenMin,(Float_t)CenMax,kTRUE,"V0M"))));//kTRUE is for Run2

  mgr->AddTask(task);

  const TString outputFileName = AliAnalysisManager::GetCommonFileName();
  const TString dirname = Form("PWGDQ_LMEE_Cen%d_%d_%s",CenMin,CenMax,triggername.Data());

  //create output container
  AliAnalysisDataContainer *coutput1 =
    mgr->CreateContainer(Form("Tree_Cen%d_%d_%s",CenMin,CenMax,triggername.Data()),
                         TTree::Class(),
                         AliAnalysisManager::kExchangeContainer,
                         Form("%s:%s",outputFileName.Data(),dirname.Data()));

  AliAnalysisDataContainer *cOutputHist1 =
    mgr->CreateContainer(Form("Histos_Cen%d_%d_%s",CenMin,CenMax,triggername.Data()),
                         TList::Class(),
                         AliAnalysisManager::kOutputContainer,
                         Form("%s:%s",outputFileName.Data(),dirname.Data()));

  AliAnalysisDataContainer *cOutputHist2 =
    mgr->CreateContainer(Form("CF_Cen%d_%d_%s",CenMin,CenMax,triggername.Data()),
                         TList::Class(),
                         AliAnalysisManager::kOutputContainer,
                         Form("%s:%s",outputFileName.Data(),dirname.Data()));

  AliAnalysisDataContainer *cOutputHist3 =
    mgr->CreateContainer(Form("EventStat_Cen%d_%d_%s",CenMin,CenMax,triggername.Data()),
                         TH1D::Class(),
                         AliAnalysisManager::kOutputContainer,
                         Form("%s:%s",outputFileName.Data(),dirname.Data()));

  mgr->ConnectInput(task,  0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 0, coutput1 );
  mgr->ConnectOutput(task, 1, cOutputHist1);
  mgr->ConnectOutput(task, 2, cOutputHist2);
  mgr->ConnectOutput(task, 3, cOutputHist3);

  return task;
}

<commit_msg>PWGDQ/LMEE: quick fix for obj name in AddTask<commit_after>AliAnalysisTask *AddTask_dsekihat_lowmass_PbPb(
    Bool_t getFromAlien = kFALSE,
    TString cFileName = "Config_dsekihat_lowmass_PbPb.C",
    TString lFileName = "LMEECutLib_dsekihat.C",
		TString calibFileName = "",
    UInt_t trigger = AliVEvent::kINT7|AliVEvent::kCentral|AliVEvent::kSemiCentral,
    const Int_t CenMin =  0,
    const Int_t CenMax = 10,
    const Int_t Nmix   = 10,
    const Float_t PtMin = 0.2,
    const Float_t PtMax = 10,
    const Float_t EtaMin = -0.8,
    const Float_t EtaMax = +0.8
    )
{
  //get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTask_dsekihat_lowmass_PbPb", "No analysis manager found.");
    return 0;
  }

  //Base Directory for GRID / LEGO Train
  TString configBasePath= "$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/";
  //TString configBasePath= "./";
  if(getFromAlien
    && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/macrosLMEE/%s .",cFileName.Data())))
    && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/macrosLMEE/%s .",lFileName.Data())))
    ){
    configBasePath=Form("%s/",gSystem->pwd());
  }

  TString configFilePath(configBasePath + cFileName);
  TString libFilePath(configBasePath + lFileName);
  std::cout << "Configpath:  " << configFilePath << std::endl;
  std::cout << "Libpath:  "    << libFilePath << std::endl;

  TString triggername = "NULL";
  if(trigger == (UInt_t)AliVEvent::kINT7)             triggername = "kINT7";
  else if(trigger == (UInt_t)AliVEvent::kCentral)     triggername = "kCentral";
  else if(trigger == (UInt_t)AliVEvent::kSemiCentral) triggername = "kSemiCentral";
  else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral | AliVEvent::kSemiCentral)) triggername = "kCombinedCentralityTriggers";
  else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral))                           triggername = "kCombinedCentral";
  else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kSemiCentral))                       triggername = "kCombinedSemiCentral";

  //create task and add it to the manager (MB)
  AliAnalysisTaskMultiDielectron *task = new AliAnalysisTaskMultiDielectron(Form("MultiDielectron_Cen%d_%d_%s",CenMin,CenMax,triggername.Data()));
  task->UsePhysicsSelection(kTRUE);
  task->SetTriggerMask(trigger);

  //add dielectron analysis with different cuts to the task
  gROOT->LoadMacro(libFilePath.Data());//library first
  gROOT->LoadMacro(configFilePath.Data());

  //const Int_t nDie = (Int_t)gROOT->ProcessLine("GetN()");
  const Int_t nTC  = Int_t(gROOT->ProcessLine("GetNTC()") );
  const Int_t nPID = Int_t(gROOT->ProcessLine("GetNPID()"));
  const Int_t nPF  = Int_t(gROOT->ProcessLine("GetNPF()") );

  THnF *hs_mean_TPC_El  = 0x0;
  THnF *hs_width_TPC_El = 0x0;
  THnF *hs_mean_ITS_El  = 0x0;
  THnF *hs_width_ITS_El = 0x0;
  THnF *hs_mean_TOF_El  = 0x0;
  THnF *hs_width_TOF_El = 0x0;
  THnF *hs_mean_TPC_Pi  = 0x0;
  THnF *hs_width_TPC_Pi = 0x0;

	TFile *rootfile = 0x0;
	if(calibFileName != ""){
		printf("reading : %s for PID calibration\n",calibFileName.Data());
		rootfile = TFile::Open(calibFileName,"READ");
		hs_mean_TPC_El  = (THnF*)rootfile->Get("hs_mean_TPC_El");
		hs_width_TPC_El = (THnF*)rootfile->Get("hs_width_TPC_El");
		hs_mean_ITS_El  = (THnF*)rootfile->Get("hs_mean_ITS_El");
		hs_width_ITS_El = (THnF*)rootfile->Get("hs_width_ITS_El");
		hs_mean_TOF_El  = (THnF*)rootfile->Get("hs_mean_TOF_El");
		hs_width_TOF_El = (THnF*)rootfile->Get("hs_width_TOF_El");
		hs_mean_TPC_Pi  = (THnF*)rootfile->Get("hs_mean_TPC_Pi");
		hs_width_TPC_Pi = (THnF*)rootfile->Get("hs_width_TPC_Pi");
	}

  for (Int_t itc=0; itc<nTC; ++itc){
    for (Int_t ipid=0; ipid<nPID; ++ipid){
      for (Int_t ipf=0; ipf<nPF; ++ipf){
        AliDielectron *diel = reinterpret_cast<AliDielectron*>(gROOT->ProcessLine(Form("Config_dsekihat_lowmass_PbPb(%d,%d,%d,%f,%f,%f,%f)",itc,ipid,ipf,PtMin,PtMax,EtaMin,EtaMax)));
        if(!diel) continue;

        //AliDielectronVarCuts*  centCuts = new AliDielectronVarCuts("centCuts",Form("kPbPb%02d%02d",CenMin,CenMax));
        //centCuts->AddCut(AliDielectronVarManager::kCentralityNew, (Float_t)CenMin, (Float_t)CenMax);
        //diel->GetEventFilter().AddCuts(centCuts);

				//if(calibFileName!=""){
				if(rootfile && rootfile->IsOpen()){
					diel->SetPIDCaibinPU(kTRUE);
					//for electron
					diel->SetCentroidCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kElectron,hs_mean_TPC_El ,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM);
					diel->   SetWidthCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kElectron,hs_width_TPC_El,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM);
					diel->SetCentroidCorrFunctionPU(AliDielectronPID::kITS,AliPID::kElectron,hs_mean_ITS_El ,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM);
					diel->   SetWidthCorrFunctionPU(AliDielectronPID::kITS,AliPID::kElectron,hs_width_ITS_El,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM);
					diel->SetCentroidCorrFunctionPU(AliDielectronPID::kTOF,AliPID::kElectron,hs_mean_TOF_El ,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM);
					diel->   SetWidthCorrFunctionPU(AliDielectronPID::kTOF,AliPID::kElectron,hs_width_TOF_El,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM);
					//for pion
					diel->SetCentroidCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kPion,hs_mean_TPC_Pi ,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM);
					diel->   SetWidthCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kPion,hs_width_TPC_Pi ,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM);
				}

        TString name = diel->GetName();
        if(name.Contains("PIDCalib",TString::kIgnoreCase) || name.Contains("noPID",TString::kIgnoreCase)){
          printf("No event mixing handler for post PID calibration/noPID\n");
        }
        else{
          printf("Add event mixing handler\n");
          AliDielectronMixingHandler *mix = new AliDielectronMixingHandler;
          mix->SetMixType(AliDielectronMixingHandler::kAll);
          mix->AddVariable(AliDielectronVarManager::kZvPrim,"-10., -8., -6., -4., -2. , 0., 2., 4., 6., 8. , 10.");
          mix->AddVariable(AliDielectronVarManager::kCentralityNew,"0,5,10,30,50,70,90,101");
          mix->AddVariable(AliDielectronVarManager::kNacc,"0,10000");
          mix->SetDepth(Nmix);
          diel->SetMixingHandler(mix);
        }
        task->AddDielectron(diel);
      }//pre-filter loop
    }//PID loop
  }//track cut loop

	//if(rootfile && rootfile->IsOpen()) rootfile->Close();

  task->SetEventFilter(reinterpret_cast<AliDielectronEventCuts*>(gROOT->ProcessLine(Form("LMEECutLib::SetupEventCuts(%f,%f,%d,\"%s\")",(Float_t)CenMin,(Float_t)CenMax,kTRUE,"V0M"))));//kTRUE is for Run2

  mgr->AddTask(task);

  const TString outputFileName = AliAnalysisManager::GetCommonFileName();
  const TString dirname = Form("PWGDQ_LMEE_Cen%d_%d_%s",CenMin,CenMax,triggername.Data());

  //create output container
  AliAnalysisDataContainer *coutput1 =
    mgr->CreateContainer(Form("Tree_Cen%d_%d_%s",CenMin,CenMax,triggername.Data()),
                         TTree::Class(),
                         AliAnalysisManager::kExchangeContainer,
                         Form("%s:%s",outputFileName.Data(),dirname.Data()));

  AliAnalysisDataContainer *cOutputHist1 =
    mgr->CreateContainer(Form("Histos_Cen%d_%d_%s",CenMin,CenMax,triggername.Data()),
                         TList::Class(),
                         AliAnalysisManager::kOutputContainer,
                         Form("%s:%s",outputFileName.Data(),dirname.Data()));

  AliAnalysisDataContainer *cOutputHist2 =
    mgr->CreateContainer(Form("CF_Cen%d_%d_%s",CenMin,CenMax,triggername.Data()),
                         TList::Class(),
                         AliAnalysisManager::kOutputContainer,
                         Form("%s:%s",outputFileName.Data(),dirname.Data()));

  AliAnalysisDataContainer *cOutputHist3 =
    mgr->CreateContainer(Form("EventStat_Cen%d_%d_%s",CenMin,CenMax,triggername.Data()),
                         TH1D::Class(),
                         AliAnalysisManager::kOutputContainer,
                         Form("%s:%s",outputFileName.Data(),dirname.Data()));

  mgr->ConnectInput(task,  0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 0, coutput1 );
  mgr->ConnectOutput(task, 1, cOutputHist1);
  mgr->ConnectOutput(task, 2, cOutputHist2);
  mgr->ConnectOutput(task, 3, cOutputHist3);

  return task;
}

<|endoftext|>


<commit_before>/*
 *  ofxBullet.cpp
 *  Bullet
 *
 *  Created by Todd Vanderlin on 2/5/11.
 *  Copyright 2011 Interactive Design. All rights reserved.
 *
 */

#include "ofxBullet.h"

bool callback::needBroadphaseCollision(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1) const
{

	if( proxy0->m_collisionFilterGroup == 2 && proxy1->m_collisionFilterGroup == 2) {
		return false;
	}

	return true;
}

static bool removeRigidBody(ofxBulletRigidBody * b) {
	bool remove = true;
	if(b!=NULL) {
		remove = b->bDestroy;
		if(remove) {
			b->destroy();
			delete b;
			b = NULL;
		}
	}
	return remove;
}

ofxBullet::ofxBullet() {
	world = NULL;
	ground = NULL;
}

//--------------------------------------------------------------
ofxBullet::~ofxBullet() {
	destroy();
}

//--------------------------------------------------------------
void ofxBullet::init() {

	// collision configuration contains default setup
	// for memory, collision setup. Advanced users
	// can create their own configuration.
	collisionConfiguration = new btDefaultCollisionConfiguration();

	// use the default collision dispatcher. For
	// parallel processing you can use a diffent
	// dispatcher (see Extras/BulletMultiThreaded)
	dispatcher = new btCollisionDispatcher(collisionConfiguration);

	// btDbvtBroadphase is a good general purpose
	// broadphase. You can also try out btAxis3Sweep.
	overlappingPairCache = new btDbvtBroadphase();

	// the default constraint solver. For parallel
	// processing you can use a different solver
	// (see Extras/BulletMultiThreaded)
	solver = new btSequentialImpulseConstraintSolver;
	world  = new btDiscreteDynamicsWorld(dispatcher,
										 overlappingPairCache,
										 solver,
										 collisionConfiguration);
}

//--------------------------------------------------------------
void ofxBullet::destroy() {

	if(world == NULL) return;

	// cleanup in the reverse order of creation/initialization
	// remove the bodies from the dynamics world and delete them
	for (int i = world->getNumCollisionObjects()-1; i >= 0 ; i--) {

		btCollisionObject* obj = world->getCollisionObjectArray()[i];
		btRigidBody* body = btRigidBody::upcast(obj);

		if (body) {
			if(body->getMotionState()) {
				delete body->getMotionState();
			}
		}

		world->removeCollisionObject( obj );
		delete obj;

	}
	/*
	 }

	 for (int i = 0; i < rigidBodies.size(); i++) {
	 btCollisionShape* shape = rigidBodies[i]->shape;
	 delete shape;

	 }
	 */

	/*delete world;
	 delete solver;
	 delete overlappingPairCache;
	 delete dispatcher;
	 delete collisionConfiguration;
	 */
}

//--------------------------------------------------------------
void ofxBullet::update() {

	if(world == NULL) return;
	float dt = ofGetElapsedTimeMillis() * 0.00001f;
	world->stepSimulation( dt );

	rigidBodies.erase(rigidBodies.begin(), partition(rigidBodies.begin(), rigidBodies.end(), removeRigidBody));

}

//--------------------------------------------------------------
void ofxBullet::draw() {

	//glPushMatrix();
	//glTranslated(0, 0, 0);
	//glScalef(SCALE, SCALE, SCALE);

	for	(int i=0; i<rigidBodies.size(); i++) {
		ofSetColor(255, 0, 255);
		rigidBodies[i]->draw();
	}

	//glPopMatrix();

}

//--------------------------------------------------------------
void ofxBullet::drawFloor() {
	//glPushMatrix();
	//glTranslated(0, 0, 0);
	//glScalef(SCALE, SCALE, SCALE);
	if (ground) {
		ground->draw();
	}
	//glPopMatrix();
}

//--------------------------------------------------------------
void ofxBullet::addBody(ofxBulletRigidBody * b) {

	if(b == NULL) return;

}

//--------------------------------------------------------------
void ofxBullet::createGround(float size) {

	btTransform startTransform;
	startTransform.setIdentity();
	startTransform.setOrigin(btVector3(0, 0, 0));

	ground = new ofxBulletRigidBody();
	ground->world = world;

	ground->shape = new btBoxShape(btVector3(btScalar(size/SCALE),
											 btScalar(2.0/SCALE),
											 btScalar(size/SCALE)));

	//b->shape = new btSphereShape(radius/SCALE);
	ground->createRigidBody(0, startTransform);

	world->addRigidBody(ground->body);
	//rigidBodies.push_back(ground);
}

//--------------------------------------------------------------
ofxBulletRigidBody * ofxBullet::createSphere(ofVec3f pos, float radius, float mass) {

	btTransform startTransform;
	startTransform.setIdentity();
	startTransform.setOrigin(btVector3(pos.x/SCALE, pos.y/SCALE, pos.z/SCALE));

	ofxBulletRigidBody * b = new ofxBulletRigidBody();
	b->world = world;
	b->shape = new btSphereShape(radius/SCALE);
	b->createRigidBody(mass, startTransform);

	world->addRigidBody(b->body);
	rigidBodies.push_back(b);

	return b;
}

//--------------------------------------------------------------
ofxBulletRigidBody * ofxBullet::createBox(ofVec3f pos, ofVec3f size, float mass) {

	btTransform startTransform;
	startTransform.setIdentity();
	startTransform.setOrigin(btVector3(pos.x/SCALE, pos.y/SCALE, pos.z/SCALE));

	ofxBulletRigidBody * b = new ofxBulletRigidBody();
	b->world = world;

	size /= SCALE;
	b->shape = new btBoxShape(btVector3(size.x, size.y, size.z));
	b->createRigidBody(mass, startTransform);

	world->addRigidBody(b->body);
	rigidBodies.push_back(b);

	return b;
}

//--------------------------------------------------------------
ofxBulletRigidBody * ofxBullet::createCone(ofVec3f pos, float radius, float height, float mass) {

	btTransform startTransform;
	startTransform.setIdentity();
	startTransform.setOrigin(btVector3(pos.x/SCALE, pos.y/SCALE, pos.z/SCALE));

	ofxBulletRigidBody * b = new ofxBulletRigidBody();
	b->world = world;
	b->shape = new btConeShape(radius/SCALE, height/SCALE);
	b->createRigidBody(mass, startTransform);

	world->addRigidBody(b->body);
	rigidBodies.push_back(b);

	return b;
}

//--------------------------------------------------------------
//---------------- NEED TO CLEAN UP ----------------------
//-------------------RIP FROM BULLET---------------------------------
//--------------------------------------------------------------

//--------------------------------------------------------------
btVector3 ofxBullet::getRayTo(int x, int y, ofCamera * cam) {

	y = ofMap(y, 0, ofGetHeight(), ofGetHeight(), 0);
	float adjustx = fabs((ofGetWidth()/2)-x);
	float adjusty = fabs((ofGetHeight()/2)-y);
	adjustx = ofMap(adjustx, 0, ofGetWidth()/2, 0, ofGetWidth()/5);
	adjusty = ofMap(adjusty, 0, ofGetHeight()/2, 0, ofGetHeight()/5);
	if (x > ofGetWidth()/2) adjustx = -adjustx;
	if (y > ofGetHeight()/2) adjusty = -adjusty;
	x += adjustx; y+= adjusty;

	float top = 1.f;
	float bottom = -1.f;
	float nearPlane = 1.f;
	float tanFov = (top-bottom)*0.5f / nearPlane;
	float fov = 2.0 * atanf (tanFov);

	ofVec3f campos = cam->getGlobalPosition();

	btVector3 rayFrom = btVector3(campos.x, campos.y, campos.z);
	ofVec3f dir = cam->getLookAtDir();
	btVector3 rayForward = btVector3(dir.x, dir.y, dir.z);
	rayForward.normalize();
	float farPlane = 10000.f;
	rayForward *= farPlane;

	btVector3 rightOffset;
	ofVec3f camup = cam->getUpDir();
	btVector3 vertical = btVector3(camup.x, camup.y, camup.z);

	btVector3 hor;
	hor = rayForward.cross(vertical);
	hor.normalize();
	vertical = hor.cross(rayForward);
	vertical.normalize();
	vertical = -vertical;

	float tanfov = tanf(0.5f*fov);

	hor *= 2.f * farPlane * tanfov;
	vertical *= 2.f * farPlane * tanfov;

	btScalar aspect;

	if (ofGetWidth() > ofGetHeight()) {
		aspect = ofGetWidth() / (btScalar)ofGetHeight();
		hor*=aspect;
	} else 	{
		aspect = ofGetHeight() / (btScalar)ofGetWidth();
		vertical*=aspect;
	}

	btVector3 rayToCenter = rayFrom + rayForward;
	btVector3 dHor = hor * 1.f/float(ofGetWidth());
	btVector3 dVert = vertical * 1.f/float(ofGetHeight());

	btVector3 rayTo = rayToCenter - 0.5f * hor + 0.5f * vertical;
	rayTo += x * dHor;
	rayTo -= y * dVert;
	return rayTo;
}

//--------------------------------------------------------------
btScalar mousePickClamp = 30.f;
btVector3 hitPos(-1,-1,-1);
float oldPickingDist  = 0.f;
btVector3 oldPickingPos;
btTypedConstraint*						m_pickConstraint;		// constraint for mouse picking
btRigidBody*							pickedBody;

void ofxBullet::mousePressed(int x, int y){

	if (world != NULL) {

		btVector3 rayTo   = getRayTo(x, y, camera);
		ofVec3f campos    = camera->getGlobalPosition();
		btVector3 rayFrom = btVector3(campos.x, campos.y, campos.z);

		btCollisionWorld::ClosestRayResultCallback rayCallback(rayFrom,rayTo);
		world->rayTest(rayFrom, rayTo, rayCallback);

		if (rayCallback.hasHit()) {

			btRigidBody * body = btRigidBody::upcast(rayCallback.m_collisionObject);

			if (body) {

				//other exclusions?
				if (!(body->isStaticObject() || body->isKinematicObject())) {

					printf("Hit\n");

					pickedBody = body;
					pickedBody->setActivationState(DISABLE_DEACTIVATION);

					btVector3 pickPos = rayCallback.m_hitPointWorld;
					printf("pickPos=%f,%f,%f\n",pickPos.getX(),pickPos.getY(),pickPos.getZ());

					btVector3 localPivot = body->getCenterOfMassTransform().inverse() * pickPos;

					btPoint2PointConstraint* p2p = new btPoint2PointConstraint(*body,localPivot);
					p2p->m_setting.m_impulseClamp = oldPickingDist;

					world->addConstraint(p2p);
					m_pickConstraint = p2p;

					//save mouse position for dragging
					oldPickingPos = rayTo;
					hitPos = pickPos;

					oldPickingDist  = (pickPos-rayFrom).length();

					//very weak constraint for picking
					p2p->m_setting.m_tau = 0.1f;
				}
			}
		}
	}
}

//--------------------------------------------------------------
void ofxBullet::mouseReleased(int x, int y){

	if (m_pickConstraint && world) {
		printf("removed");
		world->removeConstraint(m_pickConstraint);
		//delete m_pickConstraint;
		//printf("removed constraint %i",gPickingConstraintId);
		m_pickConstraint = 0;
		pickedBody->forceActivationState(ACTIVE_TAG);
		pickedBody->setDeactivationTime( 0.f );
		pickedBody = 0;
	}

}
//--------------------------------------------------------------
void ofxBullet::mouseDragged(int x, int y){

	if (m_pickConstraint) {
		//move the constraint pivot
		btPoint2PointConstraint* p2p = static_cast<btPoint2PointConstraint*>(m_pickConstraint);

		if (p2p) {
			//keep it at the same picking distance

			btVector3 newRayTo = getRayTo(x, y, camera);
			btVector3 rayFrom;
			btVector3 oldPivotInB = p2p->getPivotInB();
			btVector3 newPivotB;

			ofVec3f campos = camera->getGlobalPosition();
			rayFrom = btVector3(campos.x, campos.y, campos.z);
			btVector3 dir = newRayTo-rayFrom;
			dir.normalize();
			dir *= oldPickingDist;

			newPivotB = rayFrom + dir;

			p2p->setPivotB(newPivotB);
		}

	}
}

<commit_msg>attractors added<commit_after>/*
 *  ofxBullet.cpp
 *  Bullet
 *
 *  Created by Todd Vanderlin on 2/5/11.
 *  Copyright 2011 Interactive Design. All rights reserved.
 *
 */

#include "ofxBullet.h"

bool callback::needBroadphaseCollision(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1) const
{

	if( proxy0->m_collisionFilterGroup == 2 && proxy1->m_collisionFilterGroup == 2) {
		return false;
	}

	return true;
}

static bool removeRigidBody(ofxBulletRigidBody * b) {
	bool remove = true;
	if(b!=NULL) {
		remove = b->bDestroy;
		if(remove) {
			b->destroy();
			delete b;
			b = NULL;
		}
	}
	return remove;
}

ofxBullet::ofxBullet() {
	world = NULL;
	ground = NULL;
}

//--------------------------------------------------------------
ofxBullet::~ofxBullet() {
	destroy();
}

//--------------------------------------------------------------
void ofxBullet::init() {

	// collision configuration contains default setup
	// for memory, collision setup. Advanced users
	// can create their own configuration.
	collisionConfiguration = new btDefaultCollisionConfiguration();

	// use the default collision dispatcher. For
	// parallel processing you can use a diffent
	// dispatcher (see Extras/BulletMultiThreaded)
	dispatcher = new btCollisionDispatcher(collisionConfiguration);

	// btDbvtBroadphase is a good general purpose
	// broadphase. You can also try out btAxis3Sweep.
	overlappingPairCache = new btDbvtBroadphase();

	// the default constraint solver. For parallel
	// processing you can use a different solver
	// (see Extras/BulletMultiThreaded)
	solver = new btSequentialImpulseConstraintSolver;
	world  = new btDiscreteDynamicsWorld(dispatcher,
										 overlappingPairCache,
										 solver,
										 collisionConfiguration);
}

//--------------------------------------------------------------
void ofxBullet::destroy() {

	if(world == NULL) return;

	// cleanup in the reverse order of creation/initialization
	// remove the bodies from the dynamics world and delete them
	for (int i = world->getNumCollisionObjects()-1; i >= 0 ; i--) {

		btCollisionObject* obj = world->getCollisionObjectArray()[i];
		btRigidBody* body = btRigidBody::upcast(obj);

		if (body) {
			if(body->getMotionState()) {
				delete body->getMotionState();
			}
		}

		world->removeCollisionObject( obj );
		delete obj;

	}
	/*
	 }

	 for (int i = 0; i < rigidBodies.size(); i++) {
	 btCollisionShape* shape = rigidBodies[i]->shape;
	 delete shape;

	 }
	 */

	/*delete world;
	 delete solver;
	 delete overlappingPairCache;
	 delete dispatcher;
	 delete collisionConfiguration;
	 */
}

//--------------------------------------------------------------
void ofxBullet::update() {

	if(world == NULL) return;
	float dt = ofGetElapsedTimeMillis() * 0.00001f;
	solveConstraints();
	world->stepSimulation( dt );

	rigidBodies.erase(rigidBodies.begin(), partition(rigidBodies.begin(), rigidBodies.end(), removeRigidBody));

}

//--------------------------------------------------------------
void ofxBullet::draw() {

	//glPushMatrix();
	//glTranslated(0, 0, 0);
	//glScalef(SCALE, SCALE, SCALE);

	for	(int i=0; i<rigidBodies.size(); i++) {
		ofSetColor(255, 0, 255);
		rigidBodies[i]->draw();
	}

	//glPopMatrix();

}

//--------------------------------------------------------------
void ofxBullet::drawFloor() {
	//glPushMatrix();
	//glTranslated(0, 0, 0);
	//glScalef(SCALE, SCALE, SCALE);
	if (ground) {
		ground->draw();
	}
	//glPopMatrix();
}

//--------------------------------------------------------------
void ofxBullet::addBody(ofxBulletRigidBody * b) {

	if(b == NULL) return;

}

//--------------------------------------------------------------
void ofxBullet::createGround(float size) {

	btTransform startTransform;
	startTransform.setIdentity();
	startTransform.setOrigin(btVector3(0, 0, 0));

	ground = new ofxBulletRigidBody();
	ground->world = world;

	ground->shape = new btBoxShape(btVector3(btScalar(size/SCALE),
											 btScalar(2.0/SCALE),
											 btScalar(size/SCALE)));

	//b->shape = new btSphereShape(radius/SCALE);
	ground->createRigidBody(0, startTransform);

	world->addRigidBody(ground->body);
	//rigidBodies.push_back(ground);
}

//--------------------------------------------------------------
ofxBulletRigidBody * ofxBullet::createSphere(ofVec3f pos, float radius, float mass) {

	btTransform startTransform;
	startTransform.setIdentity();
	startTransform.setOrigin(btVector3(pos.x/SCALE, pos.y/SCALE, pos.z/SCALE));

	ofxBulletRigidBody * b = new ofxBulletRigidBody();
	b->world = world;
	b->shape = new btSphereShape(radius/SCALE);
	b->createRigidBody(mass, startTransform);

	world->addRigidBody(b->body);
	rigidBodies.push_back(b);

	return b;
}

//--------------------------------------------------------------
ofxBulletRigidBody * ofxBullet::createBox(ofVec3f pos, ofVec3f size, float mass) {

	btTransform startTransform;
	startTransform.setIdentity();
	startTransform.setOrigin(btVector3(pos.x/SCALE, pos.y/SCALE, pos.z/SCALE));

	ofxBulletRigidBody * b = new ofxBulletRigidBody();
	b->world = world;

	size /= SCALE;
	b->shape = new btBoxShape(btVector3(size.x, size.y, size.z));
	b->createRigidBody(mass, startTransform);

	world->addRigidBody(b->body);
	rigidBodies.push_back(b);

	return b;
}

//--------------------------------------------------------------
ofxBulletRigidBody * ofxBullet::createCone(ofVec3f pos, float radius, float height, float mass) {

	btTransform startTransform;
	startTransform.setIdentity();
	startTransform.setOrigin(btVector3(pos.x/SCALE, pos.y/SCALE, pos.z/SCALE));

	ofxBulletRigidBody * b = new ofxBulletRigidBody();
	b->world = world;
	b->shape = new btConeShape(radius/SCALE, height/SCALE);
	b->createRigidBody(mass, startTransform);

	world->addRigidBody(b->body);
	rigidBodies.push_back(b);

	return b;
}

//--------------------------------------------------------------
//---------------- NEED TO CLEAN UP ----------------------
//-------------------RIP FROM BULLET---------------------------------
//--------------------------------------------------------------

//--------------------------------------------------------------
btVector3 ofxBullet::getRayTo(int x, int y, ofCamera * cam) {

	y = ofMap(y, 0, ofGetHeight(), ofGetHeight(), 0);
	float adjustx = fabs((ofGetWidth()/2)-x);
	float adjusty = fabs((ofGetHeight()/2)-y);
	adjustx = ofMap(adjustx, 0, ofGetWidth()/2, 0, ofGetWidth()/5);
	adjusty = ofMap(adjusty, 0, ofGetHeight()/2, 0, ofGetHeight()/5);
	if (x > ofGetWidth()/2) adjustx = -adjustx;
	if (y > ofGetHeight()/2) adjusty = -adjusty;
	x += adjustx; y+= adjusty;

	float top = 1.f;
	float bottom = -1.f;
	float nearPlane = 1.f;
	float tanFov = (top-bottom)*0.5f / nearPlane;
	float fov = 2.0 * atanf (tanFov);

	ofVec3f campos = cam->getGlobalPosition();

	btVector3 rayFrom = btVector3(campos.x, campos.y, campos.z);
	ofVec3f dir = cam->getLookAtDir();
	btVector3 rayForward = btVector3(dir.x, dir.y, dir.z);
	rayForward.normalize();
	float farPlane = 10000.f;
	rayForward *= farPlane;

	btVector3 rightOffset;
	ofVec3f camup = cam->getUpDir();
	btVector3 vertical = btVector3(camup.x, camup.y, camup.z);

	btVector3 hor;
	hor = rayForward.cross(vertical);
	hor.normalize();
	vertical = hor.cross(rayForward);
	vertical.normalize();
	vertical = -vertical;

	float tanfov = tanf(0.5f*fov);

	hor *= 2.f * farPlane * tanfov;
	vertical *= 2.f * farPlane * tanfov;

	btScalar aspect;

	if (ofGetWidth() > ofGetHeight()) {
		aspect = ofGetWidth() / (btScalar)ofGetHeight();
		hor*=aspect;
	} else 	{
		aspect = ofGetHeight() / (btScalar)ofGetWidth();
		vertical*=aspect;
	}

	btVector3 rayToCenter = rayFrom + rayForward;
	btVector3 dHor = hor * 1.f/float(ofGetWidth());
	btVector3 dVert = vertical * 1.f/float(ofGetHeight());

	btVector3 rayTo = rayToCenter - 0.5f * hor + 0.5f * vertical;
	rayTo += x * dHor;
	rayTo -= y * dVert;
	return rayTo;
}

//--------------------------------------------------------------
btScalar mousePickClamp = 30.f;
btVector3 hitPos(-1,-1,-1);
float oldPickingDist  = 0.f;
btVector3 oldPickingPos;
btTypedConstraint*						m_pickConstraint;		// constraint for mouse picking
btRigidBody*							pickedBody;

void ofxBullet::mousePressed(int x, int y){

	if (world != NULL) {

		btVector3 rayTo   = getRayTo(x, y, camera);
		ofVec3f campos    = camera->getGlobalPosition();
		btVector3 rayFrom = btVector3(campos.x, campos.y, campos.z);

		btCollisionWorld::ClosestRayResultCallback rayCallback(rayFrom,rayTo);
		world->rayTest(rayFrom, rayTo, rayCallback);

		if (rayCallback.hasHit()) {

			btRigidBody * body = btRigidBody::upcast(rayCallback.m_collisionObject);

			if (body) {

				//other exclusions?
				if (!(body->isStaticObject() || body->isKinematicObject())) {

					printf("Hit\n");

					pickedBody = body;
					pickedBody->setActivationState(DISABLE_DEACTIVATION);

					btVector3 pickPos = rayCallback.m_hitPointWorld;
					printf("pickPos=%f,%f,%f\n",pickPos.getX(),pickPos.getY(),pickPos.getZ());

					btVector3 localPivot = body->getCenterOfMassTransform().inverse() * pickPos;

					btPoint2PointConstraint* p2p = new btPoint2PointConstraint(*body,localPivot);
					p2p->m_setting.m_impulseClamp = oldPickingDist;

					world->addConstraint(p2p);
					m_pickConstraint = p2p;

					//save mouse position for dragging
					oldPickingPos = rayTo;
					hitPos = pickPos;

					oldPickingDist  = (pickPos-rayFrom).length();

					//very weak constraint for picking
					p2p->m_setting.m_tau = 0.1f;
				}
			}
		}
	}
}

//--------------------------------------------------------------
void ofxBullet::mouseReleased(int x, int y){

	if (m_pickConstraint && world) {
		printf("removed");
		world->removeConstraint(m_pickConstraint);
		//delete m_pickConstraint;
		//printf("removed constraint %i",gPickingConstraintId);
		m_pickConstraint = 0;
		pickedBody->forceActivationState(ACTIVE_TAG);
		pickedBody->setDeactivationTime( 0.f );
		pickedBody = 0;
	}

}
//--------------------------------------------------------------
void ofxBullet::mouseDragged(int x, int y){

	if (m_pickConstraint) {
		//move the constraint pivot
		btPoint2PointConstraint* p2p = static_cast<btPoint2PointConstraint*>(m_pickConstraint);

		if (p2p) {
			//keep it at the same picking distance

			btVector3 newRayTo = getRayTo(x, y, camera);
			btVector3 rayFrom;
			btVector3 oldPivotInB = p2p->getPivotInB();
			btVector3 newPivotB;

			ofVec3f campos = camera->getGlobalPosition();
			rayFrom = btVector3(campos.x, campos.y, campos.z);
			btVector3 dir = newRayTo-rayFrom;
			dir.normalize();
			dir *= oldPickingDist;

			newPivotB = rayFrom + dir;

			p2p->setPivotB(newPivotB);
		}

	}
}

ofxBulletBaseConstraint * ofxBullet::addAttractor(ofxBulletRigidBody * a, ofxBulletRigidBody * b, float force)
{
	constraints.push_back( new ofxBulletRBtoRBAttractor() );
	int me = constraints.size()-1;
	((ofxBulletRBtoRBAttractor*)(constraints[ me ]))->setup(a, b, force);
}

//--------------------------------------------------------------
void ofxBullet::solveConstraints()
{
	if(constraints.size() <= 0) return;

	// clean up -- must check both objects are not set for destruction!
	for(int i = constraints.size()-1; i >=0; i--)
	{
		if( constraints[i]->shouldDestroy() ){
			constraints.erase(constraints.begin()+i);
		}
	}

	// solve constraints
	for(int i = 0; i <constraints.size(); i++) constraints[i]->solve();

}

void ofxBullet::clearConstraints()
{
	for(int i = 0; i <constraints.size(); i++)
	{
		delete constraints[i];
	}
	constraints.clear();
}
//--------------------------------------------------------------
void ofxBullet::clearAttractions(ofxBulletRigidBody * a)
{
	for(int i = 0; i <constraints.size(); i++)
	{
		if(constraints[i]->getType() == constraintTypeAttraction)
		{
			if( ((ofxBulletRBtoRBAttractor*)(constraints[ i ]))->getA() == a)
			{
				constraints[i]->kill();
			}
		}
	}
}

<|endoftext|>


<commit_before>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"

class AutoConstructTest:
  public testing::Test
{};

namespace {
  class HasDefaultCtorAndOthers {
  public:
    HasDefaultCtorAndOthers(void) :
      v(101)
    {}
    HasDefaultCtorAndOthers(int v) :
      v(v)
    {}

    const int v;
  };
}

TEST_F(AutoConstructTest, AutoConstructNoArgs) {
  AutoConstruct<HasDefaultCtorAndOthers> hdcao;
  ASSERT_EQ(101, hdcao->v) << "Default constructor was not called as expected";
}

TEST_F(AutoConstructTest, AutoConstructWithArgs) {
  AutoConstruct<HasDefaultCtorAndOthers> hdcao(495);
  ASSERT_EQ(495, hdcao->v) << "Constructor call was not made as expected";
}

class CanOnlyAcceptMovedInput {
public:
  CanOnlyAcceptMovedInput(std::unique_ptr<std::shared_ptr<int>>&& ptr) :
    m_ptr(std::move(ptr))
  {}

  std::unique_ptr<std::shared_ptr<int>> m_ptr;
};

TEST_F(AutoConstructTest, CanConstructRvalueCtor) {
  auto originalPtr = std::make_shared<int>(555);

  // Make a unique pointer to a shared pointer, and pass it in:
  {
    AutoCreateContext ctxt;
    CurrentContextPusher pshr(ctxt);

    std::unique_ptr<std::shared_ptr<int>> forwarded{new std::shared_ptr<int>(originalPtr)};
    AutoConstruct<CanOnlyAcceptMovedInput> coami(std::move(forwarded));

    // Should have the correct number of references, no more and no less
    ASSERT_EQ(2UL, originalPtr.use_count()) << "Forwarding unique pointer did not correctly";
  }

  ASSERT_TRUE(originalPtr.unique()) << "Memory leak detected due to incorrect forwarding of a unique pointer";
}

TEST_F(AutoConstructTest, CanCopyAutoConstruct) {
  AutoConstruct<HasDefaultCtorAndOthers> v(100);
}

namespace {
  class MyPrivateCtorClass {
    MyPrivateCtorClass(void):
      ival(-10)
    {}
    MyPrivateCtorClass(int ival) :
      ival(ival)
    {}

  public:
    const int ival;

    static MyPrivateCtorClass* New(int ival) {
      return new MyPrivateCtorClass{ ival };
    }
  };
}

TEST_F(AutoConstructTest, FactoryNewPrivateCtor) {
  AutoConstruct<MyPrivateCtorClass> mpcc{ 1002 };
  ASSERT_NE(nullptr, mpcc.get()) << "Null not expected as a return type from a factory new construction";
  ASSERT_EQ(1002, mpcc->ival) << "Correct ctor was not invoked on a type with a private ctor";
}
<commit_msg>Forgot to inherit CoreObject<commit_after>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"

class AutoConstructTest:
  public testing::Test
{};

namespace {
  class HasDefaultCtorAndOthers {
  public:
    HasDefaultCtorAndOthers(void) :
      v(101)
    {}
    HasDefaultCtorAndOthers(int v) :
      v(v)
    {}

    const int v;
  };
}

TEST_F(AutoConstructTest, AutoConstructNoArgs) {
  AutoConstruct<HasDefaultCtorAndOthers> hdcao;
  ASSERT_EQ(101, hdcao->v) << "Default constructor was not called as expected";
}

TEST_F(AutoConstructTest, AutoConstructWithArgs) {
  AutoConstruct<HasDefaultCtorAndOthers> hdcao(495);
  ASSERT_EQ(495, hdcao->v) << "Constructor call was not made as expected";
}

class CanOnlyAcceptMovedInput {
public:
  CanOnlyAcceptMovedInput(std::unique_ptr<std::shared_ptr<int>>&& ptr) :
    m_ptr(std::move(ptr))
  {}

  std::unique_ptr<std::shared_ptr<int>> m_ptr;
};

TEST_F(AutoConstructTest, CanConstructRvalueCtor) {
  auto originalPtr = std::make_shared<int>(555);

  // Make a unique pointer to a shared pointer, and pass it in:
  {
    AutoCreateContext ctxt;
    CurrentContextPusher pshr(ctxt);

    std::unique_ptr<std::shared_ptr<int>> forwarded{new std::shared_ptr<int>(originalPtr)};
    AutoConstruct<CanOnlyAcceptMovedInput> coami(std::move(forwarded));

    // Should have the correct number of references, no more and no less
    ASSERT_EQ(2UL, originalPtr.use_count()) << "Forwarding unique pointer did not correctly";
  }

  ASSERT_TRUE(originalPtr.unique()) << "Memory leak detected due to incorrect forwarding of a unique pointer";
}

TEST_F(AutoConstructTest, CanCopyAutoConstruct) {
  AutoConstruct<HasDefaultCtorAndOthers> v(100);
}

namespace {
  class MyPrivateCtorClass:
    public CoreObject
  {
    MyPrivateCtorClass(void):
      ival(-10)
    {}
    MyPrivateCtorClass(int ival) :
      ival(ival)
    {}

  public:
    const int ival;

    static MyPrivateCtorClass* New(int ival) {
      return new MyPrivateCtorClass{ ival };
    }
  };
}

TEST_F(AutoConstructTest, FactoryNewPrivateCtor) {
  AutoConstruct<MyPrivateCtorClass> mpcc{ 1002 };
  ASSERT_NE(nullptr, mpcc.get()) << "Null not expected as a return type from a factory new construction";
  ASSERT_EQ(1002, mpcc->ival) << "Correct ctor was not invoked on a type with a private ctor";
}
<|endoftext|>


<commit_before>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software;  you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/

#include <string>
#include <vector>
#include "bzfio.h"
#include "common.h"
#ifdef _WIN32

#include <windows.h>

std::vector<HINSTANCE>	vLibHandles;

void loadPlugin ( std::string plugin, std::string config )
{
	int (*lpProc)(const char*);

	HINSTANCE	hLib = LoadLibrary(plugin.c_str());
	if (hLib)
	{
		lpProc = (int (__cdecl *)(const char*))GetProcAddress(hLib, "bz_Load");
		if (lpProc)
		{
			int ret =lpProc(config.c_str());
			DEBUG1("Plugin:%s loaded",plugin.c_str());
			vLibHandles.push_back(hLib);
		}
		else
			DEBUG1("Plugin:%s found but does not contain bz_Load method",plugin.c_str());
	}
	else
		DEBUG1("Plugin:%s not found",plugin.c_str());
}

void unloadPlugins ( void )
{
	int (*lpProc)(void);
	for (unsigned int i = 0; i < vLibHandles.size();i++)
	{
		lpProc = (int (__cdecl *)(void))GetProcAddress(vLibHandles[i], "bz_Unload");
		if (lpProc)
			int ret =lpProc();
		else
			DEBUG1("Plugin does not contain bz_UnLoad method");

		FreeLibrary(vLibHandles[i]);
	}

	vLibHandles.clear();
}

#else

#include <dlfcn.h>
std::vector<void*>	vLibHandles;

void loadPlugin ( std::string plugin, std::string config )
{
	int (*lpProc)(const char*);

	void*	hLib = dlopen(plugin.c_str(),RTLD_LAZY);
	if (hLib)
	{
		l*(void**) &lpProc = dlsym(hLib,"bz_Load");
		if (lpProc)
		{
			(*lpProc)(config.c_str());
			DEBUG1("Plugin:%s loaded",plugin.c_str());
			vLibHandles.push_back(hLib);
		}
		else
			DEBUG1("Plugin:%s found but does not contain bz_Load method",plugin.c_str());
	}
	else
		DEBUG1("Plugin:%s not found",plugin.c_str());
}

void unloadPlugins ( void )
{
	int (*lpProc)(void);
	for (unsigned int i = 0; i < vLibHandles.size();i++)
	{
		*(void**) &lpProc = dlsym(vLibHandles[i], "bz_Unload");
		if (lpProc)
			(*lpProc)();
		else
			DEBUG1("Plugin does not contain bz_UnLoad method");

		dlclose(vLibHandles[i]);
	}
	vLibHandles.clear();
}
#endif

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>more debug info<commit_after>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software;  you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/

#include <string>
#include <vector>
#include "bzfio.h"
#include "common.h"
#ifdef _WIN32

#include <windows.h>

std::vector<HINSTANCE>	vLibHandles;

void loadPlugin ( std::string plugin, std::string config )
{
	int (*lpProc)(const char*);

	HINSTANCE	hLib = LoadLibrary(plugin.c_str());
	if (hLib)
	{
		lpProc = (int (__cdecl *)(const char*))GetProcAddress(hLib, "bz_Load");
		if (lpProc)
		{
			int ret =lpProc(config.c_str());
			DEBUG1("Plugin:%s loaded\n",plugin.c_str());
			vLibHandles.push_back(hLib);
		}
		else
			DEBUG1("Plugin:%s found but does not contain bz_Load method\n",plugin.c_str());
	}
	else
		DEBUG1("Plugin:%s not found\n",plugin.c_str());
}

void unloadPlugins ( void )
{
	int (*lpProc)(void);
	for (unsigned int i = 0; i < vLibHandles.size();i++)
	{
		lpProc = (int (__cdecl *)(void))GetProcAddress(vLibHandles[i], "bz_Unload");
		if (lpProc)
			int ret =lpProc();
		else
			DEBUG1("Plugin does not contain bz_UnLoad method\n");

		FreeLibrary(vLibHandles[i]);
	}

	vLibHandles.clear();
}

#else

#include <dlfcn.h>
std::vector<void*>	vLibHandles;

void loadPlugin ( std::string plugin, std::string config )
{
	int (*lpProc)(const char*);

	void*	hLib = dlopen(plugin.c_str(),RTLD_LAZY);
	if (hLib)
	{
		*(void**) &lpProc = dlsym(hLib,"bz_Load");
		if (lpProc)
		{
			(*lpProc)(config.c_str());
			DEBUG1("Plugin:%s loaded\n",plugin.c_str());
			vLibHandles.push_back(hLib);
		}
		else
			DEBUG1("Plugin:%s found but does not contain bz_Load method, error %s\n",plugin.c_str(),dlerror());
	}
	else
		DEBUG1("Plugin:%s not found, error %s\n",plugin.c_str(), dlerror());
}

void unloadPlugins ( void )
{
	int (*lpProc)(void);
	for (unsigned int i = 0; i < vLibHandles.size();i++)
	{
		*(void**) &lpProc = dlsym(vLibHandles[i], "bz_Unload");
		if (lpProc)
			(*lpProc)();
		else
			DEBUG1("Plugin does not contain bz_UnLoad method, error %s\n",dlerror());

		dlclose(vLibHandles[i]);
	}
	vLibHandles.clear();
}
#endif

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>// Scintilla source code edit control
/** @file LexMSSQL.cxx
 ** Lexer for MSSQL.
 **/
// By Filip Yaghob <fyaghob@gmail.com>

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

#define KW_MSSQL_STATEMENTS         0
#define KW_MSSQL_DATA_TYPES         1
#define KW_MSSQL_SYSTEM_TABLES      2
#define KW_MSSQL_GLOBAL_VARIABLES   3
#define KW_MSSQL_FUNCTIONS          4
#define KW_MSSQL_STORED_PROCEDURES  5
#define KW_MSSQL_OPERATORS          6

static bool isMSSQLOperator(char ch) {
	if (isascii(ch) && isalnum(ch))
		return false;
	// '.' left out as it is used to make up numbers
	if (ch == '%' || ch == '^' || ch == '&' || ch == '*' ||
        ch == '-' || ch == '+' || ch == '=' || ch == '|' ||
        ch == '<' || ch == '>' || ch == '/' ||
        ch == '!' || ch == '~' || ch == '(' || ch == ')' ||
		ch == ',')
		return true;
	return false;
}

static char classifyWordSQL(unsigned int start,
                            unsigned int end,
                            WordList *keywordlists[],
                            Accessor &styler,
                            unsigned int actualState,
							unsigned int prevState) {
	char s[256];
	bool wordIsNumber = isdigit(styler[start]) || (styler[start] == '.');

	WordList &kwStatements          = *keywordlists[KW_MSSQL_STATEMENTS];
    WordList &kwDataTypes           = *keywordlists[KW_MSSQL_DATA_TYPES];
    WordList &kwSystemTables        = *keywordlists[KW_MSSQL_SYSTEM_TABLES];
    WordList &kwGlobalVariables     = *keywordlists[KW_MSSQL_GLOBAL_VARIABLES];
    WordList &kwFunctions           = *keywordlists[KW_MSSQL_FUNCTIONS];
    WordList &kwStoredProcedures    = *keywordlists[KW_MSSQL_STORED_PROCEDURES];
    WordList &kwOperators           = *keywordlists[KW_MSSQL_OPERATORS];

	for (unsigned int i = 0; i < end - start + 1 && i < 128; i++) {
		s[i] = static_cast<char>(tolower(styler[start + i]));
		s[i + 1] = '\0';
	}
	char chAttr = SCE_MSSQL_IDENTIFIER;

	if (actualState == SCE_MSSQL_GLOBAL_VARIABLE) {

        if (kwGlobalVariables.InList(&s[2]))
            chAttr = SCE_MSSQL_GLOBAL_VARIABLE;

	} else if (wordIsNumber) {
		chAttr = SCE_MSSQL_NUMBER;

	} else if (prevState == SCE_MSSQL_DEFAULT_PREF_DATATYPE) {
		// Look first in datatypes
        if (kwDataTypes.InList(s))
            chAttr = SCE_MSSQL_DATATYPE;
		else if (kwOperators.InList(s))
			chAttr = SCE_MSSQL_OPERATOR;
		else if (kwStatements.InList(s))
			chAttr = SCE_MSSQL_STATEMENT;
		else if (kwSystemTables.InList(s))
			chAttr = SCE_MSSQL_SYSTABLE;
		else if (kwFunctions.InList(s))
            chAttr = SCE_MSSQL_FUNCTION;
		else if (kwStoredProcedures.InList(s))
			chAttr = SCE_MSSQL_STORED_PROCEDURE;

	} else {
		if (kwOperators.InList(s))
			chAttr = SCE_MSSQL_OPERATOR;
		else if (kwStatements.InList(s))
			chAttr = SCE_MSSQL_STATEMENT;
		else if (kwSystemTables.InList(s))
			chAttr = SCE_MSSQL_SYSTABLE;
		else if (kwFunctions.InList(s))
			chAttr = SCE_MSSQL_FUNCTION;
		else if (kwStoredProcedures.InList(s))
			chAttr = SCE_MSSQL_STORED_PROCEDURE;
		else if (kwDataTypes.InList(s))
			chAttr = SCE_MSSQL_DATATYPE;
	}

	styler.ColourTo(end, chAttr);

	return chAttr;
}

static void ColouriseMSSQLDoc(unsigned int startPos, int length,
                              int initStyle, WordList *keywordlists[], Accessor &styler) {

	styler.StartAt(startPos);

	bool fold = styler.GetPropertyInt("fold") != 0;
	int lineCurrent = styler.GetLine(startPos);
	int spaceFlags = 0;

	int state = initStyle;
	int prevState = initStyle;
	char chPrev = ' ';
	char chNext = styler[startPos];
	styler.StartSegment(startPos);
	unsigned int lengthDoc = startPos + length;
	for (unsigned int i = startPos; i < lengthDoc; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);

		if ((ch == '\r' && chNext != '\n') || (ch == '\n')) {
			int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags);
			int lev = indentCurrent;
			if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {
				// Only non whitespace lines can be headers
				int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags);
				if (indentCurrent < (indentNext & ~SC_FOLDLEVELWHITEFLAG)) {
					lev |= SC_FOLDLEVELHEADERFLAG;
				}
			}
			if (fold) {
				styler.SetLevel(lineCurrent, lev);
			}
		}

		if (styler.IsLeadByte(ch)) {
			chNext = styler.SafeGetCharAt(i + 2);
			chPrev = ' ';
			i += 1;
			continue;
		}

		// When the last char isn't part of the state (have to deal with it too)...
		if ( (state == SCE_MSSQL_IDENTIFIER) ||
                    (state == SCE_MSSQL_STORED_PROCEDURE) ||
                    (state == SCE_MSSQL_DATATYPE) ||
                    //~ (state == SCE_MSSQL_COLUMN_NAME) ||
                    (state == SCE_MSSQL_FUNCTION) ||
                    //~ (state == SCE_MSSQL_GLOBAL_VARIABLE) ||
                    (state == SCE_MSSQL_VARIABLE)) {
			if (!iswordchar(ch)) {
				int stateTmp;

                if ((state == SCE_MSSQL_VARIABLE) || (state == SCE_MSSQL_COLUMN_NAME)) {
                    styler.ColourTo(i - 1, state);
					stateTmp = state;
                } else
                    stateTmp = classifyWordSQL(styler.GetStartSegment(), i - 1, keywordlists, styler, state, prevState);

				prevState = state;

				if (stateTmp == SCE_MSSQL_IDENTIFIER || stateTmp == SCE_MSSQL_VARIABLE)
					state = SCE_MSSQL_DEFAULT_PREF_DATATYPE;
				else
					state = SCE_MSSQL_DEFAULT;
			}
		} else if (state == SCE_MSSQL_LINE_COMMENT) {
			if (ch == '\r' || ch == '\n') {
				styler.ColourTo(i - 1, state);
				prevState = state;
				state = SCE_MSSQL_DEFAULT;
			}
		} else if (state == SCE_MSSQL_GLOBAL_VARIABLE) {
			if ((ch != '@') && !iswordchar(ch)) {
				classifyWordSQL(styler.GetStartSegment(), i - 1, keywordlists, styler, state, prevState);
				prevState = state;
				state = SCE_MSSQL_DEFAULT;
			}
		}

		// If is the default or one of the above succeeded
		if (state == SCE_MSSQL_DEFAULT || state == SCE_MSSQL_DEFAULT_PREF_DATATYPE) {
			if (iswordstart(ch)) {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_IDENTIFIER;
			} else if (ch == '/' && chNext == '*') {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_COMMENT;
			} else if (ch == '-' && chNext == '-') {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_LINE_COMMENT;
			} else if (ch == '\'') {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_STRING;
			} else if (ch == '"') {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_COLUMN_NAME;
			} else if (ch == '[') {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_COLUMN_NAME_2;
			} else if (isMSSQLOperator(ch)) {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				styler.ColourTo(i, SCE_MSSQL_OPERATOR);
                //~ style = SCE_MSSQL_DEFAULT;
				prevState = state;
				state = SCE_MSSQL_DEFAULT;
			} else if (ch == '@') {
                styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
                if (chNext == '@') {
                    state = SCE_MSSQL_GLOBAL_VARIABLE;
//                    i += 2;
                } else
                    state = SCE_MSSQL_VARIABLE;
            }

		// When the last char is part of the state...
		} else if (state == SCE_MSSQL_COMMENT) {
				if (ch == '/' && chPrev == '*') {
					if (((i > (styler.GetStartSegment() + 2)) || ((initStyle == SCE_MSSQL_COMMENT) &&
					    (styler.GetStartSegment() == startPos)))) {
						styler.ColourTo(i, state);
						//~ state = SCE_MSSQL_COMMENT;
					prevState = state;
                        state = SCE_MSSQL_DEFAULT;
					}
				}
			} else if (state == SCE_MSSQL_STRING) {
				if (ch == '\'') {
					if ( chNext == '\'' ) {
						i++;
					ch = chNext;
					chNext = styler.SafeGetCharAt(i + 1);
					} else {
						styler.ColourTo(i, state);
					prevState = state;
						state = SCE_MSSQL_DEFAULT;
					//i++;
					}
				//ch = chNext;
				//chNext = styler.SafeGetCharAt(i + 1);
				}
			} else if (state == SCE_MSSQL_COLUMN_NAME) {
				if (ch == '"') {
					if (chNext == '"') {
						i++;
					ch = chNext;
					chNext = styler.SafeGetCharAt(i + 1);
				} else {
                    styler.ColourTo(i, state);
					prevState = state;
					state = SCE_MSSQL_DEFAULT_PREF_DATATYPE;
					//i++;
                }
                }
		} else if (state == SCE_MSSQL_COLUMN_NAME_2) {
			if (ch == ']') {
                styler.ColourTo(i, state);
				prevState = state;
                state = SCE_MSSQL_DEFAULT_PREF_DATATYPE;
                //i++;
			}
		}

		chPrev = ch;
	}
	styler.ColourTo(lengthDoc - 1, state);
}

static void FoldMSSQLDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) {
	bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
	bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
	unsigned int endPos = startPos + length;
	int visibleChars = 0;
	int lineCurrent = styler.GetLine(startPos);
	int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
	int levelCurrent = levelPrev;
	char chNext = styler[startPos];
	bool inComment = (styler.StyleAt(startPos-1) == SCE_MSSQL_COMMENT);
    char s[10];
	for (unsigned int i = startPos; i < endPos; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);
		int style = styler.StyleAt(i);
		bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
        // Comment folding
		if (foldComment) {
			if (!inComment && (style == SCE_MSSQL_COMMENT))
				levelCurrent++;
			else if (inComment && (style != SCE_MSSQL_COMMENT))
				levelCurrent--;
			inComment = (style == SCE_MSSQL_COMMENT);
		}
        if (style == SCE_MSSQL_STATEMENT) {
            // Folding between begin and end
            if (ch == 'b' || ch == 'e') {
                for (unsigned int j = 0; j < 5; j++) {
					if (!iswordchar(styler[i + j])) {
						break;
					}
					s[j] = styler[i + j];
					s[j + 1] = '\0';
                }
				if (strcmp(s, "begin") == 0) {
					levelCurrent++;
				}
				if (strcmp(s, "end") == 0) {
					levelCurrent--;
				}
            }
        }
		if (atEOL) {
			int lev = levelPrev;
			if (visibleChars == 0 && foldCompact)
				lev |= SC_FOLDLEVELWHITEFLAG;
			if ((levelCurrent > levelPrev) && (visibleChars > 0))
				lev |= SC_FOLDLEVELHEADERFLAG;
			if (lev != styler.LevelAt(lineCurrent)) {
				styler.SetLevel(lineCurrent, lev);
			}
			lineCurrent++;
			levelPrev = levelCurrent;
			visibleChars = 0;
		}
		if (!isspacechar(ch))
			visibleChars++;
	}
	// Fill in the real level of the next line, keeping the current flags as they will be filled in later
	int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
	styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}

static const char * const sqlWordListDesc[] = {
	"Statements",
    "Data Types",
    "System tables",
    "Global variables",
    "Functions",
    "System Stored Procedures",
    "Operators",
	0,
};

LexerModule lmMSSQL(SCLEX_MSSQL, ColouriseMSSQLDoc, "mssql", FoldMSSQLDoc, sqlWordListDesc);
<commit_msg>Added license reference to help the picky.<commit_after>// Scintilla source code edit control
/** @file LexMSSQL.cxx
 ** Lexer for MSSQL.
 **/
// By Filip Yaghob <fyaghob@gmail.com>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

#define KW_MSSQL_STATEMENTS         0
#define KW_MSSQL_DATA_TYPES         1
#define KW_MSSQL_SYSTEM_TABLES      2
#define KW_MSSQL_GLOBAL_VARIABLES   3
#define KW_MSSQL_FUNCTIONS          4
#define KW_MSSQL_STORED_PROCEDURES  5
#define KW_MSSQL_OPERATORS          6

static bool isMSSQLOperator(char ch) {
	if (isascii(ch) && isalnum(ch))
		return false;
	// '.' left out as it is used to make up numbers
	if (ch == '%' || ch == '^' || ch == '&' || ch == '*' ||
        ch == '-' || ch == '+' || ch == '=' || ch == '|' ||
        ch == '<' || ch == '>' || ch == '/' ||
        ch == '!' || ch == '~' || ch == '(' || ch == ')' ||
		ch == ',')
		return true;
	return false;
}

static char classifyWordSQL(unsigned int start,
                            unsigned int end,
                            WordList *keywordlists[],
                            Accessor &styler,
                            unsigned int actualState,
							unsigned int prevState) {
	char s[256];
	bool wordIsNumber = isdigit(styler[start]) || (styler[start] == '.');

	WordList &kwStatements          = *keywordlists[KW_MSSQL_STATEMENTS];
    WordList &kwDataTypes           = *keywordlists[KW_MSSQL_DATA_TYPES];
    WordList &kwSystemTables        = *keywordlists[KW_MSSQL_SYSTEM_TABLES];
    WordList &kwGlobalVariables     = *keywordlists[KW_MSSQL_GLOBAL_VARIABLES];
    WordList &kwFunctions           = *keywordlists[KW_MSSQL_FUNCTIONS];
    WordList &kwStoredProcedures    = *keywordlists[KW_MSSQL_STORED_PROCEDURES];
    WordList &kwOperators           = *keywordlists[KW_MSSQL_OPERATORS];

	for (unsigned int i = 0; i < end - start + 1 && i < 128; i++) {
		s[i] = static_cast<char>(tolower(styler[start + i]));
		s[i + 1] = '\0';
	}
	char chAttr = SCE_MSSQL_IDENTIFIER;

	if (actualState == SCE_MSSQL_GLOBAL_VARIABLE) {

        if (kwGlobalVariables.InList(&s[2]))
            chAttr = SCE_MSSQL_GLOBAL_VARIABLE;

	} else if (wordIsNumber) {
		chAttr = SCE_MSSQL_NUMBER;

	} else if (prevState == SCE_MSSQL_DEFAULT_PREF_DATATYPE) {
		// Look first in datatypes
        if (kwDataTypes.InList(s))
            chAttr = SCE_MSSQL_DATATYPE;
		else if (kwOperators.InList(s))
			chAttr = SCE_MSSQL_OPERATOR;
		else if (kwStatements.InList(s))
			chAttr = SCE_MSSQL_STATEMENT;
		else if (kwSystemTables.InList(s))
			chAttr = SCE_MSSQL_SYSTABLE;
		else if (kwFunctions.InList(s))
            chAttr = SCE_MSSQL_FUNCTION;
		else if (kwStoredProcedures.InList(s))
			chAttr = SCE_MSSQL_STORED_PROCEDURE;

	} else {
		if (kwOperators.InList(s))
			chAttr = SCE_MSSQL_OPERATOR;
		else if (kwStatements.InList(s))
			chAttr = SCE_MSSQL_STATEMENT;
		else if (kwSystemTables.InList(s))
			chAttr = SCE_MSSQL_SYSTABLE;
		else if (kwFunctions.InList(s))
			chAttr = SCE_MSSQL_FUNCTION;
		else if (kwStoredProcedures.InList(s))
			chAttr = SCE_MSSQL_STORED_PROCEDURE;
		else if (kwDataTypes.InList(s))
			chAttr = SCE_MSSQL_DATATYPE;
	}

	styler.ColourTo(end, chAttr);

	return chAttr;
}

static void ColouriseMSSQLDoc(unsigned int startPos, int length,
                              int initStyle, WordList *keywordlists[], Accessor &styler) {

	styler.StartAt(startPos);

	bool fold = styler.GetPropertyInt("fold") != 0;
	int lineCurrent = styler.GetLine(startPos);
	int spaceFlags = 0;

	int state = initStyle;
	int prevState = initStyle;
	char chPrev = ' ';
	char chNext = styler[startPos];
	styler.StartSegment(startPos);
	unsigned int lengthDoc = startPos + length;
	for (unsigned int i = startPos; i < lengthDoc; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);

		if ((ch == '\r' && chNext != '\n') || (ch == '\n')) {
			int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags);
			int lev = indentCurrent;
			if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {
				// Only non whitespace lines can be headers
				int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags);
				if (indentCurrent < (indentNext & ~SC_FOLDLEVELWHITEFLAG)) {
					lev |= SC_FOLDLEVELHEADERFLAG;
				}
			}
			if (fold) {
				styler.SetLevel(lineCurrent, lev);
			}
		}

		if (styler.IsLeadByte(ch)) {
			chNext = styler.SafeGetCharAt(i + 2);
			chPrev = ' ';
			i += 1;
			continue;
		}

		// When the last char isn't part of the state (have to deal with it too)...
		if ( (state == SCE_MSSQL_IDENTIFIER) ||
                    (state == SCE_MSSQL_STORED_PROCEDURE) ||
                    (state == SCE_MSSQL_DATATYPE) ||
                    //~ (state == SCE_MSSQL_COLUMN_NAME) ||
                    (state == SCE_MSSQL_FUNCTION) ||
                    //~ (state == SCE_MSSQL_GLOBAL_VARIABLE) ||
                    (state == SCE_MSSQL_VARIABLE)) {
			if (!iswordchar(ch)) {
				int stateTmp;

                if ((state == SCE_MSSQL_VARIABLE) || (state == SCE_MSSQL_COLUMN_NAME)) {
                    styler.ColourTo(i - 1, state);
					stateTmp = state;
                } else
                    stateTmp = classifyWordSQL(styler.GetStartSegment(), i - 1, keywordlists, styler, state, prevState);

				prevState = state;

				if (stateTmp == SCE_MSSQL_IDENTIFIER || stateTmp == SCE_MSSQL_VARIABLE)
					state = SCE_MSSQL_DEFAULT_PREF_DATATYPE;
				else
					state = SCE_MSSQL_DEFAULT;
			}
		} else if (state == SCE_MSSQL_LINE_COMMENT) {
			if (ch == '\r' || ch == '\n') {
				styler.ColourTo(i - 1, state);
				prevState = state;
				state = SCE_MSSQL_DEFAULT;
			}
		} else if (state == SCE_MSSQL_GLOBAL_VARIABLE) {
			if ((ch != '@') && !iswordchar(ch)) {
				classifyWordSQL(styler.GetStartSegment(), i - 1, keywordlists, styler, state, prevState);
				prevState = state;
				state = SCE_MSSQL_DEFAULT;
			}
		}

		// If is the default or one of the above succeeded
		if (state == SCE_MSSQL_DEFAULT || state == SCE_MSSQL_DEFAULT_PREF_DATATYPE) {
			if (iswordstart(ch)) {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_IDENTIFIER;
			} else if (ch == '/' && chNext == '*') {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_COMMENT;
			} else if (ch == '-' && chNext == '-') {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_LINE_COMMENT;
			} else if (ch == '\'') {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_STRING;
			} else if (ch == '"') {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_COLUMN_NAME;
			} else if (ch == '[') {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_COLUMN_NAME_2;
			} else if (isMSSQLOperator(ch)) {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				styler.ColourTo(i, SCE_MSSQL_OPERATOR);
                //~ style = SCE_MSSQL_DEFAULT;
				prevState = state;
				state = SCE_MSSQL_DEFAULT;
			} else if (ch == '@') {
                styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
                if (chNext == '@') {
                    state = SCE_MSSQL_GLOBAL_VARIABLE;
//                    i += 2;
                } else
                    state = SCE_MSSQL_VARIABLE;
            }

		// When the last char is part of the state...
		} else if (state == SCE_MSSQL_COMMENT) {
				if (ch == '/' && chPrev == '*') {
					if (((i > (styler.GetStartSegment() + 2)) || ((initStyle == SCE_MSSQL_COMMENT) &&
					    (styler.GetStartSegment() == startPos)))) {
						styler.ColourTo(i, state);
						//~ state = SCE_MSSQL_COMMENT;
					prevState = state;
                        state = SCE_MSSQL_DEFAULT;
					}
				}
			} else if (state == SCE_MSSQL_STRING) {
				if (ch == '\'') {
					if ( chNext == '\'' ) {
						i++;
					ch = chNext;
					chNext = styler.SafeGetCharAt(i + 1);
					} else {
						styler.ColourTo(i, state);
					prevState = state;
						state = SCE_MSSQL_DEFAULT;
					//i++;
					}
				//ch = chNext;
				//chNext = styler.SafeGetCharAt(i + 1);
				}
			} else if (state == SCE_MSSQL_COLUMN_NAME) {
				if (ch == '"') {
					if (chNext == '"') {
						i++;
					ch = chNext;
					chNext = styler.SafeGetCharAt(i + 1);
				} else {
                    styler.ColourTo(i, state);
					prevState = state;
					state = SCE_MSSQL_DEFAULT_PREF_DATATYPE;
					//i++;
                }
                }
		} else if (state == SCE_MSSQL_COLUMN_NAME_2) {
			if (ch == ']') {
                styler.ColourTo(i, state);
				prevState = state;
                state = SCE_MSSQL_DEFAULT_PREF_DATATYPE;
                //i++;
			}
		}

		chPrev = ch;
	}
	styler.ColourTo(lengthDoc - 1, state);
}

static void FoldMSSQLDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) {
	bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
	bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
	unsigned int endPos = startPos + length;
	int visibleChars = 0;
	int lineCurrent = styler.GetLine(startPos);
	int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
	int levelCurrent = levelPrev;
	char chNext = styler[startPos];
	bool inComment = (styler.StyleAt(startPos-1) == SCE_MSSQL_COMMENT);
    char s[10];
	for (unsigned int i = startPos; i < endPos; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);
		int style = styler.StyleAt(i);
		bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
        // Comment folding
		if (foldComment) {
			if (!inComment && (style == SCE_MSSQL_COMMENT))
				levelCurrent++;
			else if (inComment && (style != SCE_MSSQL_COMMENT))
				levelCurrent--;
			inComment = (style == SCE_MSSQL_COMMENT);
		}
        if (style == SCE_MSSQL_STATEMENT) {
            // Folding between begin and end
            if (ch == 'b' || ch == 'e') {
                for (unsigned int j = 0; j < 5; j++) {
					if (!iswordchar(styler[i + j])) {
						break;
					}
					s[j] = styler[i + j];
					s[j + 1] = '\0';
                }
				if (strcmp(s, "begin") == 0) {
					levelCurrent++;
				}
				if (strcmp(s, "end") == 0) {
					levelCurrent--;
				}
            }
        }
		if (atEOL) {
			int lev = levelPrev;
			if (visibleChars == 0 && foldCompact)
				lev |= SC_FOLDLEVELWHITEFLAG;
			if ((levelCurrent > levelPrev) && (visibleChars > 0))
				lev |= SC_FOLDLEVELHEADERFLAG;
			if (lev != styler.LevelAt(lineCurrent)) {
				styler.SetLevel(lineCurrent, lev);
			}
			lineCurrent++;
			levelPrev = levelCurrent;
			visibleChars = 0;
		}
		if (!isspacechar(ch))
			visibleChars++;
	}
	// Fill in the real level of the next line, keeping the current flags as they will be filled in later
	int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
	styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}

static const char * const sqlWordListDesc[] = {
	"Statements",
    "Data Types",
    "System tables",
    "Global variables",
    "Functions",
    "System Stored Procedures",
    "Operators",
	0,
};

LexerModule lmMSSQL(SCLEX_MSSQL, ColouriseMSSQLDoc, "mssql", FoldMSSQLDoc, sqlWordListDesc);
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2011 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreD3D11VertexDeclaration.h"
#include "OgreD3D11Mappings.h"
#include "OgreD3D11HLSLProgram.h"
#include "OgreD3D11Device.h"

namespace Ogre {

	//-----------------------------------------------------------------------
	D3D11VertexDeclaration::D3D11VertexDeclaration(D3D11Device &  device)
		:
	mlpD3DDevice(device)
	, mNeedsRebuild(true)
	{

	}
	//-----------------------------------------------------------------------
	D3D11VertexDeclaration::~D3D11VertexDeclaration()
	{
        {
		    ShaderToILayoutMapIterator iter = mShaderToILayoutMap.begin();
		    ShaderToILayoutMapIterator iterE = mShaderToILayoutMap.end();

		    for ( ; iter != iterE ; iter++)
		    {
			    iter->second->Release();
		    }
        }

        {
            ShaderToInputDescIterator iter = mD3delems.begin();
            ShaderToInputDescIterator iterE = mD3delems.end();
            for( ; iter != iterE ; iter++ )
            {
                SAFE_DELETE_ARRAY(iter->second);

            }
        }

	}
	//-----------------------------------------------------------------------
	const VertexElement& D3D11VertexDeclaration::addElement(unsigned short source,
		size_t offset, VertexElementType theType,
		VertexElementSemantic semantic, unsigned short index)
	{
		mNeedsRebuild = true;
		return VertexDeclaration::addElement(source, offset, theType, semantic, index);
	}
	//-----------------------------------------------------------------------------
	const VertexElement& D3D11VertexDeclaration::insertElement(unsigned short atPosition,
		unsigned short source, size_t offset, VertexElementType theType,
		VertexElementSemantic semantic, unsigned short index)
	{
		mNeedsRebuild = true;
		return VertexDeclaration::insertElement(atPosition, source, offset, theType, semantic, index);
	}
	//-----------------------------------------------------------------------
	void D3D11VertexDeclaration::removeElement(unsigned short elem_index)
	{
		VertexDeclaration::removeElement(elem_index);
		mNeedsRebuild = true;
	}
	//-----------------------------------------------------------------------
	void D3D11VertexDeclaration::removeElement(VertexElementSemantic semantic, unsigned short index)
	{
		VertexDeclaration::removeElement(semantic, index);
		mNeedsRebuild = true;
	}
	//-----------------------------------------------------------------------
	void D3D11VertexDeclaration::removeAllElements(void)
	{
		VertexDeclaration::removeAllElements();
		mNeedsRebuild = true;
	}
	//-----------------------------------------------------------------------
	void D3D11VertexDeclaration::modifyElement(unsigned short elem_index,
		unsigned short source, size_t offset, VertexElementType theType,
		VertexElementSemantic semantic, unsigned short index)
	{
		VertexDeclaration::modifyElement(elem_index, source, offset, theType, semantic, index);
		mNeedsRebuild = true;
	}
	//-----------------------------------------------------------------------
	D3D11_INPUT_ELEMENT_DESC * D3D11VertexDeclaration::getD3DVertexDeclaration(D3D11HLSLProgram* boundVertexProgram, VertexBufferBinding* binding)
	{
		// Create D3D elements
		size_t iNumElements = boundVertexProgram->getNumInputs();

		if (mD3delems.find(boundVertexProgram) == mD3delems.end())
		{
			D3D11_INPUT_ELEMENT_DESC*  D3delems = new D3D11_INPUT_ELEMENT_DESC[iNumElements];
            ZeroMemory(D3delems, sizeof(D3D11_INPUT_ELEMENT_DESC) * iNumElements);

			unsigned int idx;
       		for (unsigned int idx = 0; idx < iNumElements; ++idx)
			{
                D3D11_SIGNATURE_PARAMETER_DESC inputDesc = boundVertexProgram->getInputParamDesc(idx);
       			VertexElementList::const_iterator i, iend;
			    iend = mElementList.end();
                bool found = false;
		        for (i = mElementList.begin(); i != iend; ++i)
                {
                    LPCSTR semanticName			= D3D11Mappings::get(i->getSemantic());
                    UINT semanticIndex			= i->getIndex();
                    if(
                        strcmp(semanticName, inputDesc.SemanticName) == 0
                        && semanticIndex == inputDesc.SemanticIndex
                      )
                    {
                        found = true;
                        break;
                    }
                }

                if(!found)
                {
                    // find by pos
                    i = mElementList.begin();
                    for (int count = 0; count < idx && i != iend; count++, ++i)
                    {
                    }
                    if (i != iend)
                    {
                        found = true;
                    }
                }

                if(!found)
                {
                    OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to set D3D11 vertex declaration" ,
                        						"D3D11VertexDeclaration::getILayoutByShader");
                }

				D3delems[idx].SemanticName			= inputDesc.SemanticName;
				D3delems[idx].SemanticIndex			= inputDesc.SemanticIndex;
				D3delems[idx].Format				= D3D11Mappings::get(i->getType());
				D3delems[idx].InputSlot				= i->getSource();
				D3delems[idx].AlignedByteOffset		= static_cast<WORD>(i->getOffset());
				D3delems[idx].InputSlotClass		= D3D11_INPUT_PER_VERTEX_DATA;
				D3delems[idx].InstanceDataStepRate	= 0;

				VertexBufferBinding::VertexBufferBindingMap::const_iterator foundIter;
				foundIter = binding->getBindings().find(i->getSource());
				if ( foundIter != binding->getBindings().end() )
				{
					HardwareVertexBufferSharedPtr bufAtSlot = foundIter->second;
					if ( bufAtSlot->getIsInstanceData() )
					{
						D3delems[idx].InputSlotClass		= D3D11_INPUT_PER_INSTANCE_DATA;
						D3delems[idx].InstanceDataStepRate	= bufAtSlot->getInstanceDataStepRate();
					}
				}
				else
				{
					OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
						"Unable to found a bound vertex for a slot that is used in the vertex declaration." ,
						"D3D11VertexDeclaration::getD3DVertexDeclaration");

				}
			}

			mD3delems[boundVertexProgram] = D3delems;

		}

		return mD3delems[boundVertexProgram];
	}
	//-----------------------------------------------------------------------
	ID3D11InputLayout*  D3D11VertexDeclaration::getILayoutByShader(D3D11HLSLProgram* boundVertexProgram, VertexBufferBinding* binding)
	{
		ShaderToILayoutMapIterator foundIter = mShaderToILayoutMap.find(boundVertexProgram);

		ID3D11InputLayout*  pVertexLayout = 0;

		if (foundIter == mShaderToILayoutMap.end())
		{
			// if not found - create

			DWORD dwShaderFlags = 0;
			const MicroCode &  vSBuf = boundVertexProgram->getMicroCode();
            if (boundVertexProgram->getName() == "595364079_VS")
            {
                int u = 1;
            }
			D3D11_INPUT_ELEMENT_DESC * pVertexDecl=getD3DVertexDeclaration(boundVertexProgram, binding);
			HRESULT hr = mlpD3DDevice->CreateInputLayout(
				pVertexDecl,
				boundVertexProgram->getNumInputs(),
				&vSBuf[0],
				vSBuf.size(),
				&pVertexLayout );

			if (FAILED(hr)|| mlpD3DDevice.isError())
			{
				String errorDescription = mlpD3DDevice.getErrorDescription();

				OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to set D3D11 vertex declaration"+errorDescription ,
					"D3D11VertexDeclaration::getILayoutByShader");
			}

			mShaderToILayoutMap[boundVertexProgram] = pVertexLayout;

		}
		else
		{
			pVertexLayout = foundIter->second;
		}

		return pVertexLayout;
	}
	//-----------------------------------------------------------------------
	void D3D11VertexDeclaration::bindToShader(D3D11HLSLProgram* boundVertexProgram, VertexBufferBinding* binding)
	{
		ID3D11InputLayout*  pVertexLayout = getILayoutByShader(boundVertexProgram, binding);

		// Set the input layout
		mlpD3DDevice.GetImmediateContext()->IASetInputLayout( pVertexLayout);
	}
}

<commit_msg>Removed some debug code.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2011 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreD3D11VertexDeclaration.h"
#include "OgreD3D11Mappings.h"
#include "OgreD3D11HLSLProgram.h"
#include "OgreD3D11Device.h"

namespace Ogre {

	//-----------------------------------------------------------------------
	D3D11VertexDeclaration::D3D11VertexDeclaration(D3D11Device &  device)
		:
	mlpD3DDevice(device)
	, mNeedsRebuild(true)
	{

	}
	//-----------------------------------------------------------------------
	D3D11VertexDeclaration::~D3D11VertexDeclaration()
	{
        {
		    ShaderToILayoutMapIterator iter = mShaderToILayoutMap.begin();
		    ShaderToILayoutMapIterator iterE = mShaderToILayoutMap.end();

		    for ( ; iter != iterE ; iter++)
		    {
			    iter->second->Release();
		    }
        }

        {
            ShaderToInputDescIterator iter = mD3delems.begin();
            ShaderToInputDescIterator iterE = mD3delems.end();
            for( ; iter != iterE ; iter++ )
            {
                SAFE_DELETE_ARRAY(iter->second);

            }
        }

	}
	//-----------------------------------------------------------------------
	const VertexElement& D3D11VertexDeclaration::addElement(unsigned short source,
		size_t offset, VertexElementType theType,
		VertexElementSemantic semantic, unsigned short index)
	{
		mNeedsRebuild = true;
		return VertexDeclaration::addElement(source, offset, theType, semantic, index);
	}
	//-----------------------------------------------------------------------------
	const VertexElement& D3D11VertexDeclaration::insertElement(unsigned short atPosition,
		unsigned short source, size_t offset, VertexElementType theType,
		VertexElementSemantic semantic, unsigned short index)
	{
		mNeedsRebuild = true;
		return VertexDeclaration::insertElement(atPosition, source, offset, theType, semantic, index);
	}
	//-----------------------------------------------------------------------
	void D3D11VertexDeclaration::removeElement(unsigned short elem_index)
	{
		VertexDeclaration::removeElement(elem_index);
		mNeedsRebuild = true;
	}
	//-----------------------------------------------------------------------
	void D3D11VertexDeclaration::removeElement(VertexElementSemantic semantic, unsigned short index)
	{
		VertexDeclaration::removeElement(semantic, index);
		mNeedsRebuild = true;
	}
	//-----------------------------------------------------------------------
	void D3D11VertexDeclaration::removeAllElements(void)
	{
		VertexDeclaration::removeAllElements();
		mNeedsRebuild = true;
	}
	//-----------------------------------------------------------------------
	void D3D11VertexDeclaration::modifyElement(unsigned short elem_index,
		unsigned short source, size_t offset, VertexElementType theType,
		VertexElementSemantic semantic, unsigned short index)
	{
		VertexDeclaration::modifyElement(elem_index, source, offset, theType, semantic, index);
		mNeedsRebuild = true;
	}
	//-----------------------------------------------------------------------
	D3D11_INPUT_ELEMENT_DESC * D3D11VertexDeclaration::getD3DVertexDeclaration(D3D11HLSLProgram* boundVertexProgram, VertexBufferBinding* binding)
	{
		// Create D3D elements
		size_t iNumElements = boundVertexProgram->getNumInputs();

		if (mD3delems.find(boundVertexProgram) == mD3delems.end())
		{
			D3D11_INPUT_ELEMENT_DESC*  D3delems = new D3D11_INPUT_ELEMENT_DESC[iNumElements];
            ZeroMemory(D3delems, sizeof(D3D11_INPUT_ELEMENT_DESC) * iNumElements);

			unsigned int idx;
       		for (unsigned int idx = 0; idx < iNumElements; ++idx)
			{
                D3D11_SIGNATURE_PARAMETER_DESC inputDesc = boundVertexProgram->getInputParamDesc(idx);
       			VertexElementList::const_iterator i, iend;
			    iend = mElementList.end();
                bool found = false;
		        for (i = mElementList.begin(); i != iend; ++i)
                {
                    LPCSTR semanticName			= D3D11Mappings::get(i->getSemantic());
                    UINT semanticIndex			= i->getIndex();
                    if(
                        strcmp(semanticName, inputDesc.SemanticName) == 0
                        && semanticIndex == inputDesc.SemanticIndex
                      )
                    {
                        found = true;
                        break;
                    }
                }

                if(!found)
                {
                    // find by pos
                    i = mElementList.begin();
                    for (int count = 0; count < idx && i != iend; count++, ++i)
                    {
                    }
                    if (i != iend)
                    {
                        found = true;
                    }
                }

                if(!found)
                {
                    OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to set D3D11 vertex declaration" ,
                        						"D3D11VertexDeclaration::getILayoutByShader");
                }

				D3delems[idx].SemanticName			= inputDesc.SemanticName;
				D3delems[idx].SemanticIndex			= inputDesc.SemanticIndex;
				D3delems[idx].Format				= D3D11Mappings::get(i->getType());
				D3delems[idx].InputSlot				= i->getSource();
				D3delems[idx].AlignedByteOffset		= static_cast<WORD>(i->getOffset());
				D3delems[idx].InputSlotClass		= D3D11_INPUT_PER_VERTEX_DATA;
				D3delems[idx].InstanceDataStepRate	= 0;

				VertexBufferBinding::VertexBufferBindingMap::const_iterator foundIter;
				foundIter = binding->getBindings().find(i->getSource());
				if ( foundIter != binding->getBindings().end() )
				{
					HardwareVertexBufferSharedPtr bufAtSlot = foundIter->second;
					if ( bufAtSlot->getIsInstanceData() )
					{
						D3delems[idx].InputSlotClass		= D3D11_INPUT_PER_INSTANCE_DATA;
						D3delems[idx].InstanceDataStepRate	= bufAtSlot->getInstanceDataStepRate();
					}
				}
				else
				{
					OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
						"Unable to found a bound vertex for a slot that is used in the vertex declaration." ,
						"D3D11VertexDeclaration::getD3DVertexDeclaration");

				}
			}

			mD3delems[boundVertexProgram] = D3delems;

		}

		return mD3delems[boundVertexProgram];
	}
	//-----------------------------------------------------------------------
	ID3D11InputLayout*  D3D11VertexDeclaration::getILayoutByShader(D3D11HLSLProgram* boundVertexProgram, VertexBufferBinding* binding)
	{
		ShaderToILayoutMapIterator foundIter = mShaderToILayoutMap.find(boundVertexProgram);

		ID3D11InputLayout*  pVertexLayout = 0;

		if (foundIter == mShaderToILayoutMap.end())
		{
			// if not found - create

			DWORD dwShaderFlags = 0;
			const MicroCode &  vSBuf = boundVertexProgram->getMicroCode();

			D3D11_INPUT_ELEMENT_DESC * pVertexDecl=getD3DVertexDeclaration(boundVertexProgram, binding);
			HRESULT hr = mlpD3DDevice->CreateInputLayout(
				pVertexDecl,
				boundVertexProgram->getNumInputs(),
				&vSBuf[0],
				vSBuf.size(),
				&pVertexLayout );

			if (FAILED(hr)|| mlpD3DDevice.isError())
			{
				String errorDescription = mlpD3DDevice.getErrorDescription();

				OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to set D3D11 vertex declaration"+errorDescription ,
					"D3D11VertexDeclaration::getILayoutByShader");
			}

			mShaderToILayoutMap[boundVertexProgram] = pVertexLayout;

		}
		else
		{
			pVertexLayout = foundIter->second;
		}

		return pVertexLayout;
	}
	//-----------------------------------------------------------------------
	void D3D11VertexDeclaration::bindToShader(D3D11HLSLProgram* boundVertexProgram, VertexBufferBinding* binding)
	{
		ID3D11InputLayout*  pVertexLayout = getILayoutByShader(boundVertexProgram, binding);

		// Set the input layout
		mlpD3DDevice.GetImmediateContext()->IASetInputLayout( pVertexLayout);
	}
}

<|endoftext|>