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

/* $Id$ */

// Read background particles from a FLUKA boundary source file
// This is a very special generator that works for background studies for the muon-spectrometer.
// The input files come from FLUKA simulations.
// Files can be chained.
// Author: andreas.morsch@cern.ch

#include "TPDGCode.h"
#include "TDatabasePDG.h"

#include "AliGenFLUKAsource.h"
#include "AliRun.h"

#include <TFile.h>
#include <TTree.h>
#include <TChain.h>
#include <stdlib.h>
ClassImp(AliGenFLUKAsource)

AliGenFLUKAsource::AliGenFLUKAsource()
	 :AliGenerator(-1)
{
    // Constructor
    fName="FLUKA";
    fTitle="FLUKA Boundary Source";
    // Read in all particle types by default
    fIkine=6;
    // Set maximum admitted age of particles to 1.e-05 by default
    fAgeMax=1.e-05;
    // Do not add weight
    fAddWeight=1.;
    // Shift the z-coordinate of the impact point by 4.5 cm only if it reads
    // from  specific boundary source to the chamber (fZshift=4.5;),else there
    // is no need to shift as it reads boundary source for the whole volume of
    // the Muon Arm; the default value corresponds to boundary source for the
    // whole volume of the MUON Arm
    fZshift=0;
    // Set the default file
    fFileName="";

    fTreeFluka=0;
    fTreeChain = new TChain("h1");
//
//  Read all particles
    fNpart=-1;
}

AliGenFLUKAsource::AliGenFLUKAsource(Int_t npart)
    :AliGenerator(npart)
{
    // Constructor
    fName  = "FLUKA";
    fTitle = "FLUKA Boundary Source";
    // Read in all particle types by default
    fIkine=6;
    // Set maximum admitted age of particles to 1.e-05 by default
    fAgeMax=1.e-05;
    // Do not add weight
    fAddWeight=1.;
    // Shift the z-coordinate of the impact point by 4.5 cm only if it reads
    // from  specific boundary source to the chamber (fZshift=4.5;),else there
    // is no need to shift as it reads boundary source for the whole volume of
    // the Muon Arm; the default value corresponds to boundary source for the
    // whole volume of the MUON Arm
    fZshift=0;
    // Set the default file
    fFileName="";

    fTreeFluka=0;
    fTreeChain = new TChain("h1");
    fSourceId=-1;
}

AliGenFLUKAsource::AliGenFLUKAsource(const AliGenFLUKAsource & FLUKAsource):
    AliGenerator(FLUKAsource)
{
// Copy constructor
    FLUKAsource.Copy(*this);
}

//____________________________________________________________
AliGenFLUKAsource::~AliGenFLUKAsource()
{
// Destructor
 if (fTreeFluka) delete fTreeFluka;
 if (fTreeChain) delete fTreeChain;
}

void AliGenFLUKAsource::AddFile(const Text_t *filename)
{
// Add a file to the chain
    fTreeChain->Add(filename);

}

//____________________________________________________________
void AliGenFLUKAsource::FlukaInit()
{
// Set branch addresses of data entries
    TChain *h2=fTreeChain;
//Set branch addresses
    h2->SetBranchAddress("Ip",&fIp);
    h2->SetBranchAddress("Ipp",&fIpp);
    h2->SetBranchAddress("Xi",&fXi);
    h2->SetBranchAddress("Yi",&fYi);
    h2->SetBranchAddress("Zi",&fZi);
    h2->SetBranchAddress("Px",&fPx);
    h2->SetBranchAddress("Py",&fPy);
    h2->SetBranchAddress("Pz",&fPz);
    h2->SetBranchAddress("Ekin",&fEkin);
    h2->SetBranchAddress("Zv",&fZv);
    h2->SetBranchAddress("Rv",&fRv);
    h2->SetBranchAddress("Itra",&fItra);
    h2->SetBranchAddress("Igas",&fIgas);
    h2->SetBranchAddress("Wgt",&fWgt);
    h2->SetBranchAddress("Etag",&fEtag);
    h2->SetBranchAddress("Ptg",&fPtg);
    h2->SetBranchAddress("Age",&fAge);
}

//____________________________________________________________
void AliGenFLUKAsource::Generate()
{
// Generate one event

    const Int_t kIfluge[28]={kProton, kProtonBar, kElectron, kPositron,
			  kNuE, kNuEBar, kGamma, kNeutron, kNeutronBar,
			  kMuonPlus, kMuonMinus, kK0Long , kPiPlus, kPiMinus,
			  kKPlus, kKMinus, kLambda0, kLambda0Bar, kK0Short,
			  kSigmaMinus, kSigmaPlus, kSigma0, kPi0, kK0, kK0Bar,
			  0,kNuMu,kNuMuBar};
    Float_t polar[3]= {0,0,0};
  //
    Float_t origin[3];
    Float_t p[3];
    Float_t prwn;
    Float_t wgt, fwgt;
    Float_t phi;
    Float_t amass;
    Int_t iwgt;
    Int_t i, j, part, nt;
    static Int_t irwn=0;
    //
    Float_t random[2];
  //
    FlukaInit();
    TChain *h2=fTreeChain;
    Int_t nentries = (Int_t) h2->GetEntries();
    if (fNpart == -1) fNpart=Int_t(nentries*fFrac);

  // loop over number of particles
    Int_t nb=0;
    Int_t ev=gMC->CurrentEvent();
    for (i=0; i<fNpart;i++) {
	Int_t entry=fNpart*(ev-1)+i;
	nb = (Int_t)h2->GetEvent(entry);
	if (irwn > nentries) {
	    printf("No more entries in the FLUKA boundary source file\n");
	    TFile *pFile=0;
	    // Get AliRun object or create it
	    if (!gAlice) {
		gAlice = (AliRun*)pFile->Get("gAlice");
		if (gAlice) printf("AliRun object found on file\n");
		if (!gAlice) gAlice = new AliRun("gAlice","Alice test program");
	    }
	    TTree *fAli=gAlice->TreeK();
	    if (fAli) pFile =fAli->GetCurrentFile();
	    pFile->cd();
	    printf("Generate - I'm out \n");
	    return;
	}

	Int_t ifip = Int_t(fIp);

	if (fSourceId != -1 && fIgas !=fSourceId) {
	    irwn++;
	    continue;
	}

	if (ifip > 28 || ifip < 0) {
	    irwn++;
	    continue;
	}

	if ((ifip != fIkine && fIkine != kAll && fIkine != kCharged
	     && fIkine != 10) || fAge > fAgeMax){
	    irwn++;
	    continue;
	} else if (fIkine == kCharged) {
	    if (ifip == 7 || ifip == 8 || fAge > fAgeMax) {
		irwn++;
		continue;
	    }
	} else if (fIkine == kNoNeutron) {
	    if (ifip == 8 || fAge > fAgeMax) {
		irwn++;
		continue;
	    }
	}

	irwn++;
//
// PDG code from FLUKA particle type (ifip)
	part=kIfluge[int(ifip)-1];
//
// Calculate momentum from kinetic energy and mass of the particle
#if ROOT_VERSION_CODE > 197895
        amass = gMC->ParticleMass(part);
#else
	amass = (TDatabasePDG::Instance())->GetParticle(part)->Mass();
#endif
	prwn=fEkin*sqrt(1. + 2.*amass/fEkin);

	origin[0]=fYi;
	origin[1]=fXi;
	origin[2]=fZi;

	p[0]=fPy*prwn;
	p[1]=fPx*prwn;
	p[2]=fPz*prwn;

	//handle particle weight correctly
	wgt = (part == 13) ? fWgt*fAddWeight : fWgt;
	iwgt=Int_t(wgt);
	fwgt=wgt-Float_t(iwgt);
	Rndm(random,2);
	if (random[0] < fwgt) iwgt++;
	if (part==1 && iwgt>100) iwgt=100;
	Int_t nstack=0;
	for (j=0; j<iwgt; j++) {
	    PushTrack(fTrackIt,-1,part,p,origin,polar,fAge,kPPrimary,nt);
	    Rndm(random,2);
	    phi=2*random[1]*TMath::Pi();
	    Float_t pn1=p[0]*TMath::Sin(phi) - p[1]*TMath::Cos(phi);
	    Float_t pn2=p[0]*TMath::Cos(phi) + p[1]*TMath::Sin(phi);
	    p[0]=pn1;
	    p[1]=pn2;
	    Float_t on1=origin[0]*TMath::Sin(phi)-origin[1]*TMath::Cos(phi);
	    Float_t on2=origin[0]*TMath::Cos(phi)+origin[1]*TMath::Sin(phi);
	    origin[0]=on1;
	    origin[1]=on2;
	    nstack++;
	}
	if (nstack == 0) continue;
    }

    TFile *pFile=0;
// Get AliRun object or create it
    if (!gAlice) {
	gAlice = (AliRun*)pFile->Get("gAlice");
	if (gAlice) printf("AliRun object found on file\n");
	if (!gAlice) gAlice = new AliRun("gAlice","Alice test program");
    }
    TTree *fAli=gAlice->TreeK();
    if (fAli) pFile =fAli->GetCurrentFile();
    pFile->cd();
}

AliGenFLUKAsource& AliGenFLUKAsource::operator=(const  AliGenFLUKAsource& rhs)
{
// Assignment operator
    rhs.Copy(*this);
    return (*this);
}

void AliGenFLUKAsource::Copy(AliGenFLUKAsource &) const
{
    Fatal("Copy","Not implemented!\n");
}

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

/* $Id$ */

// Read background particles from a FLUKA boundary source file
// This is a very special generator that works for background studies for the muon-spectrometer.
// The input files come from FLUKA simulations.
// Files can be chained.
// Author: andreas.morsch@cern.ch

#include <RVersion.h>
#include "TPDGCode.h"
#include "TDatabasePDG.h"

#include "AliGenFLUKAsource.h"
#include "AliRun.h"

#include <TFile.h>
#include <TTree.h>
#include <TChain.h>
#include <stdlib.h>
ClassImp(AliGenFLUKAsource)

AliGenFLUKAsource::AliGenFLUKAsource()
	 :AliGenerator(-1)
{
    // Constructor
    fName="FLUKA";
    fTitle="FLUKA Boundary Source";
    // Read in all particle types by default
    fIkine=6;
    // Set maximum admitted age of particles to 1.e-05 by default
    fAgeMax=1.e-05;
    // Do not add weight
    fAddWeight=1.;
    // Shift the z-coordinate of the impact point by 4.5 cm only if it reads
    // from  specific boundary source to the chamber (fZshift=4.5;),else there
    // is no need to shift as it reads boundary source for the whole volume of
    // the Muon Arm; the default value corresponds to boundary source for the
    // whole volume of the MUON Arm
    fZshift=0;
    // Set the default file
    fFileName="";

    fTreeFluka=0;
    fTreeChain = new TChain("h1");
//
//  Read all particles
    fNpart=-1;
}

AliGenFLUKAsource::AliGenFLUKAsource(Int_t npart)
    :AliGenerator(npart)
{
    // Constructor
    fName  = "FLUKA";
    fTitle = "FLUKA Boundary Source";
    // Read in all particle types by default
    fIkine=6;
    // Set maximum admitted age of particles to 1.e-05 by default
    fAgeMax=1.e-05;
    // Do not add weight
    fAddWeight=1.;
    // Shift the z-coordinate of the impact point by 4.5 cm only if it reads
    // from  specific boundary source to the chamber (fZshift=4.5;),else there
    // is no need to shift as it reads boundary source for the whole volume of
    // the Muon Arm; the default value corresponds to boundary source for the
    // whole volume of the MUON Arm
    fZshift=0;
    // Set the default file
    fFileName="";

    fTreeFluka=0;
    fTreeChain = new TChain("h1");
    fSourceId=-1;
}

AliGenFLUKAsource::AliGenFLUKAsource(const AliGenFLUKAsource & FLUKAsource):
    AliGenerator(FLUKAsource)
{
// Copy constructor
    FLUKAsource.Copy(*this);
}

//____________________________________________________________
AliGenFLUKAsource::~AliGenFLUKAsource()
{
// Destructor
 if (fTreeFluka) delete fTreeFluka;
 if (fTreeChain) delete fTreeChain;
}

void AliGenFLUKAsource::AddFile(const Text_t *filename)
{
// Add a file to the chain
    fTreeChain->Add(filename);

}

//____________________________________________________________
void AliGenFLUKAsource::FlukaInit()
{
// Set branch addresses of data entries
    TChain *h2=fTreeChain;
//Set branch addresses
    h2->SetBranchAddress("Ip",&fIp);
    h2->SetBranchAddress("Ipp",&fIpp);
    h2->SetBranchAddress("Xi",&fXi);
    h2->SetBranchAddress("Yi",&fYi);
    h2->SetBranchAddress("Zi",&fZi);
    h2->SetBranchAddress("Px",&fPx);
    h2->SetBranchAddress("Py",&fPy);
    h2->SetBranchAddress("Pz",&fPz);
    h2->SetBranchAddress("Ekin",&fEkin);
    h2->SetBranchAddress("Zv",&fZv);
    h2->SetBranchAddress("Rv",&fRv);
    h2->SetBranchAddress("Itra",&fItra);
    h2->SetBranchAddress("Igas",&fIgas);
    h2->SetBranchAddress("Wgt",&fWgt);
    h2->SetBranchAddress("Etag",&fEtag);
    h2->SetBranchAddress("Ptg",&fPtg);
    h2->SetBranchAddress("Age",&fAge);
}

//____________________________________________________________
void AliGenFLUKAsource::Generate()
{
// Generate one event

    const Int_t kIfluge[28]={kProton, kProtonBar, kElectron, kPositron,
			  kNuE, kNuEBar, kGamma, kNeutron, kNeutronBar,
			  kMuonPlus, kMuonMinus, kK0Long , kPiPlus, kPiMinus,
			  kKPlus, kKMinus, kLambda0, kLambda0Bar, kK0Short,
			  kSigmaMinus, kSigmaPlus, kSigma0, kPi0, kK0, kK0Bar,
			  0,kNuMu,kNuMuBar};
    Float_t polar[3]= {0,0,0};
  //
    Float_t origin[3];
    Float_t p[3];
    Float_t prwn;
    Float_t wgt, fwgt;
    Float_t phi;
    Float_t amass;
    Int_t iwgt;
    Int_t i, j, part, nt;
    static Int_t irwn=0;
    //
    Float_t random[2];
  //
    FlukaInit();
    TChain *h2=fTreeChain;
    Int_t nentries = (Int_t) h2->GetEntries();
    if (fNpart == -1) fNpart=Int_t(nentries*fFrac);

  // loop over number of particles
    Int_t nb=0;
    Int_t ev=gMC->CurrentEvent();
    for (i=0; i<fNpart;i++) {
	Int_t entry=fNpart*(ev-1)+i;
	nb = (Int_t)h2->GetEvent(entry);
	if (irwn > nentries) {
	    printf("No more entries in the FLUKA boundary source file\n");
	    TFile *pFile=0;
	    // Get AliRun object or create it
	    if (!gAlice) {
		gAlice = (AliRun*)pFile->Get("gAlice");
		if (gAlice) printf("AliRun object found on file\n");
		if (!gAlice) gAlice = new AliRun("gAlice","Alice test program");
	    }
	    TTree *fAli=gAlice->TreeK();
	    if (fAli) pFile =fAli->GetCurrentFile();
	    pFile->cd();
	    printf("Generate - I'm out \n");
	    return;
	}

	Int_t ifip = Int_t(fIp);

	if (fSourceId != -1 && fIgas !=fSourceId) {
	    irwn++;
	    continue;
	}

	if (ifip > 28 || ifip < 0) {
	    irwn++;
	    continue;
	}

	if ((ifip != fIkine && fIkine != kAll && fIkine != kCharged
	     && fIkine != 10) || fAge > fAgeMax){
	    irwn++;
	    continue;
	} else if (fIkine == kCharged) {
	    if (ifip == 7 || ifip == 8 || fAge > fAgeMax) {
		irwn++;
		continue;
	    }
	} else if (fIkine == kNoNeutron) {
	    if (ifip == 8 || fAge > fAgeMax) {
		irwn++;
		continue;
	    }
	}

	irwn++;
//
// PDG code from FLUKA particle type (ifip)
	part=kIfluge[int(ifip)-1];
//
// Calculate momentum from kinetic energy and mass of the particle
#if ROOT_VERSION_CODE > 197895
        amass = gMC->ParticleMass(part);
#else
	amass = (TDatabasePDG::Instance())->GetParticle(part)->Mass();
#endif
	prwn=fEkin*sqrt(1. + 2.*amass/fEkin);

	origin[0]=fYi;
	origin[1]=fXi;
	origin[2]=fZi;

	p[0]=fPy*prwn;
	p[1]=fPx*prwn;
	p[2]=fPz*prwn;

	//handle particle weight correctly
	wgt = (part == 13) ? fWgt*fAddWeight : fWgt;
	iwgt=Int_t(wgt);
	fwgt=wgt-Float_t(iwgt);
	Rndm(random,2);
	if (random[0] < fwgt) iwgt++;
	if (part==1 && iwgt>100) iwgt=100;
	Int_t nstack=0;
	for (j=0; j<iwgt; j++) {
	    PushTrack(fTrackIt,-1,part,p,origin,polar,fAge,kPPrimary,nt);
	    Rndm(random,2);
	    phi=2*random[1]*TMath::Pi();
	    Float_t pn1=p[0]*TMath::Sin(phi) - p[1]*TMath::Cos(phi);
	    Float_t pn2=p[0]*TMath::Cos(phi) + p[1]*TMath::Sin(phi);
	    p[0]=pn1;
	    p[1]=pn2;
	    Float_t on1=origin[0]*TMath::Sin(phi)-origin[1]*TMath::Cos(phi);
	    Float_t on2=origin[0]*TMath::Cos(phi)+origin[1]*TMath::Sin(phi);
	    origin[0]=on1;
	    origin[1]=on2;
	    nstack++;
	}
	if (nstack == 0) continue;
    }

    TFile *pFile=0;
// Get AliRun object or create it
    if (!gAlice) {
	gAlice = (AliRun*)pFile->Get("gAlice");
	if (gAlice) printf("AliRun object found on file\n");
	if (!gAlice) gAlice = new AliRun("gAlice","Alice test program");
    }
    TTree *fAli=gAlice->TreeK();
    if (fAli) pFile =fAli->GetCurrentFile();
    pFile->cd();
}

AliGenFLUKAsource& AliGenFLUKAsource::operator=(const  AliGenFLUKAsource& rhs)
{
// Assignment operator
    rhs.Copy(*this);
    return (*this);
}

void AliGenFLUKAsource::Copy(AliGenFLUKAsource &) const
{
    Fatal("Copy","Not implemented!\n");
}

<|endoftext|>


<commit_before>// coding: utf-8
/* Copyright (c) 2013, Roboterclub Aachen e.V.
* All Rights Reserved.
*
* The file is part of the xpcc library and is released under the 3-clause BSD
* license. See the file `LICENSE` for the full license governing this code.
*/
// ----------------------------------------------------------------------------

//
// STM32F4DISCOVERY
// Discovery kit for STM32F407/417 lines
// http://www.st.com/web/en/catalog/tools/FM116/SC959/SS1532/PF252419
//

#ifndef XPCC_STM32_F4_DISCOVERY_HPP
#define XPCC_STM32_F4_DISCOVERY_HPP

#include <xpcc/architecture/platform.hpp>
#include <xpcc/driver/inertial/lis3dsh.hpp>

using namespace xpcc::stm32;

namespace Board
{

/// STM32F4 running at 168MHz (USB Clock qt 48MHz) generated from the
/// external on-board 8MHz crystal
typedef SystemClock<Pll<ExternalCrystal<MHz8>, MHz168, MHz48> > systemClock;

typedef GpioInputA0  Button;	// Blue PushButton
typedef GpioOutputA8 ClockOut;
typedef GpioOutputC9 SystemClockOut;

typedef GpioOutputD13 LedOrange;	// User LED 3
typedef GpioOutputD12 LedGreen;		// User LED 4
typedef GpioOutputD14 LedRed;		// User LED 5
typedef GpioOutputD15 LedBlue;		// User LED 6

namespace lis3
{
typedef GpioInputE1		Int;	// LIS302DL_INT2

typedef GpioOutputE3	Cs;		// LIS302DL_CS_I2C/SPI
typedef GpioOutputA5	Sck;	// SPI1_SCK
typedef GpioOutputA7	Mosi;	// SPI1_MOSI
typedef GpioInputA6		Miso;	// SPI1_MISO

typedef SpiMaster1 SpiMaster;
typedef xpcc::Lis3TransportSpi< SpiMaster, Cs > Transport;
}

namespace cs43
{
typedef GpioOutputA4	Lrck;	// I2S3_WS
typedef GpioOutputC7	Mclk;	// I2S3_MCK
typedef GpioOutputC10	Sclk;	// I2S3_SCK
typedef GpioOutputC12	Sdin;	// I2S3_SD

typedef GpioOutputD4	Reset;	// Audio_RST
typedef GpioB6			Scl;	// Audio_SCL
typedef GpioB9			Sda;	// Audio_SDA

typedef I2cMaster1 I2cMaster;
//typedef I2sMaster3 I2sMaster;
}

namespace mp45
{
typedef GpioOutputB10	Clk;	// CLK_IN: I2S2_CK
typedef GpioInputC3		Dout;	// PDM_OUT: I2S2_SD
//typedef I2sMaster2 I2sMaster;
}

namespace usb
{
typedef GpioA11	Dm;		// OTG_FS_DM: USB_OTG_FS_DM
typedef GpioA12	Dp;		// OTG_FS_DP: USB_OTG_FS_DP
typedef GpioA10	Id;		// OTG_FS_ID: USB_OTG_FS_ID

typedef GpioD5			Overcurrent;	// OTG_FS_OverCurrent
typedef GpioOutputC0	Power;			// OTG_FS_PowerSwitchOn
typedef GpioInputA9		VBus;			// VBUS_FS: USB_OTG_HS_VBUS
//typedef UsbFs Device;
}

inline void
initialize()
{
	systemClock::enable();
	xpcc::cortex::SysTickTimer::enable();

	LedOrange::setOutput(xpcc::Gpio::Low);
	LedGreen::setOutput(xpcc::Gpio::Low);
	LedRed::setOutput(xpcc::Gpio::Low);
	LedBlue::setOutput(xpcc::Gpio::Low);

	Button::setInput();
	Button::setInputTrigger(Gpio::InputTrigger::RisingEdge);
	Button::enableExternalInterrupt();
//	Button::enableExternalInterruptVector(12);
}

inline void
initializeLis3()
{
	lis3::Int::setInput();
	lis3::Int::setInputTrigger(Gpio::InputTrigger::RisingEdge);
	lis3::Int::enableExternalInterrupt();
//	lis3::Int::enableExternalInterruptVector(12);

	lis3::Cs::setOutput(xpcc::Gpio::High);

	lis3::Sck::connect(lis3::SpiMaster::Sck);
	lis3::Mosi::connect(lis3::SpiMaster::Mosi);
	lis3::Miso::connect(lis3::SpiMaster::Miso);

	lis3::SpiMaster::initialize<systemClock, MHz10>();
	lis3::SpiMaster::setDataMode(lis3::SpiMaster::DataMode::Mode3);
}

/// not supported yet, due to missing I2S driver
inline void
initializeCs43()
{
//	cs43::Lrck::connect(cs43::I2sMaster::Ws);
//	cs43::Mclk::connect(cs43::I2sMaster::Mck);
//	cs43::Sclk::connect(cs43::I2sMaster::Ck);
//	cs43::Sdin::connect(cs43::I2sMaster::Sd);

	cs43::Reset::setOutput(xpcc::Gpio::High);

	cs43::Scl::connect(cs43::I2cMaster::Scl);
	cs43::Sda::connect(cs43::I2cMaster::Sda);
	cs43::I2cMaster::initialize<systemClock, cs43::I2cMaster::Baudrate::Standard>();
}

/// not supported yet, due to missing I2S driver
inline void
initializeMp45()
{
//	mp45::Clk::connect(mp45::I2sMaster::Ck);
//	mp45::Dout::connect(mp45::I2sMaster::Sd);
}

/// not supported yet, due to missing USB driver
inline void
initializeUsb()
{
//	usb::Dm::connect(usb::Device::Dm);
//	usb::Dp::connect(usb::Device::Dp);
//	usb::Id::connect(usb::Device::Id);

	usb::Power::setOutput(Gpio::OutputType::PushPull, Gpio::OutputSpeed::MHz2);

	usb::Overcurrent::setInput(Gpio::InputType::Floating);
	usb::Vbus::setInput(Gpio::InputType::Floating);
}

}

#endif	// XPCC_STM32_F4_DISCOVERY_HPP
<commit_msg>Examples: STM32F4: Typo.<commit_after>// coding: utf-8
/* Copyright (c) 2013, Roboterclub Aachen e.V.
* All Rights Reserved.
*
* The file is part of the xpcc library and is released under the 3-clause BSD
* license. See the file `LICENSE` for the full license governing this code.
*/
// ----------------------------------------------------------------------------

//
// STM32F4DISCOVERY
// Discovery kit for STM32F407/417 lines
// http://www.st.com/web/en/catalog/tools/FM116/SC959/SS1532/PF252419
//

#ifndef XPCC_STM32_F4_DISCOVERY_HPP
#define XPCC_STM32_F4_DISCOVERY_HPP

#include <xpcc/architecture/platform.hpp>
#include <xpcc/driver/inertial/lis3dsh.hpp>

using namespace xpcc::stm32;

namespace Board
{

/// STM32F4 running at 168MHz (USB Clock qt 48MHz) generated from the
/// external on-board 8MHz crystal
typedef SystemClock<Pll<ExternalCrystal<MHz8>, MHz168, MHz48> > systemClock;

typedef GpioInputA0  Button;	// Blue PushButton
typedef GpioOutputA8 ClockOut;
typedef GpioOutputC9 SystemClockOut;

typedef GpioOutputD13 LedOrange;	// User LED 3
typedef GpioOutputD12 LedGreen;		// User LED 4
typedef GpioOutputD14 LedRed;		// User LED 5
typedef GpioOutputD15 LedBlue;		// User LED 6

namespace lis3
{
typedef GpioInputE1		Int;	// LIS302DL_INT2

typedef GpioOutputE3	Cs;		// LIS302DL_CS_I2C/SPI
typedef GpioOutputA5	Sck;	// SPI1_SCK
typedef GpioOutputA7	Mosi;	// SPI1_MOSI
typedef GpioInputA6		Miso;	// SPI1_MISO

typedef SpiMaster1 SpiMaster;
typedef xpcc::Lis3TransportSpi< SpiMaster, Cs > Transport;
}

namespace cs43
{
typedef GpioOutputA4	Lrck;	// I2S3_WS
typedef GpioOutputC7	Mclk;	// I2S3_MCK
typedef GpioOutputC10	Sclk;	// I2S3_SCK
typedef GpioOutputC12	Sdin;	// I2S3_SD

typedef GpioOutputD4	Reset;	// Audio_RST
typedef GpioB6			Scl;	// Audio_SCL
typedef GpioB9			Sda;	// Audio_SDA

typedef I2cMaster1 I2cMaster;
//typedef I2sMaster3 I2sMaster;
}

namespace mp45
{
typedef GpioOutputB10	Clk;	// CLK_IN: I2S2_CK
typedef GpioInputC3		Dout;	// PDM_OUT: I2S2_SD
//typedef I2sMaster2 I2sMaster;
}

namespace usb
{
typedef GpioA11	Dm;		// OTG_FS_DM: USB_OTG_FS_DM
typedef GpioA12	Dp;		// OTG_FS_DP: USB_OTG_FS_DP
typedef GpioA10	Id;		// OTG_FS_ID: USB_OTG_FS_ID

typedef GpioD5			Overcurrent;	// OTG_FS_OverCurrent
typedef GpioOutputC0	Power;			// OTG_FS_PowerSwitchOn
typedef GpioInputA9		VBus;			// VBUS_FS: USB_OTG_HS_VBUS
//typedef UsbFs Device;
}

inline void
initialize()
{
	systemClock::enable();
	xpcc::cortex::SysTickTimer::enable();

	LedOrange::setOutput(xpcc::Gpio::Low);
	LedGreen::setOutput(xpcc::Gpio::Low);
	LedRed::setOutput(xpcc::Gpio::Low);
	LedBlue::setOutput(xpcc::Gpio::Low);

	Button::setInput();
	Button::setInputTrigger(Gpio::InputTrigger::RisingEdge);
	Button::enableExternalInterrupt();
//	Button::enableExternalInterruptVector(12);
}

inline void
initializeLis3()
{
	lis3::Int::setInput();
	lis3::Int::setInputTrigger(Gpio::InputTrigger::RisingEdge);
	lis3::Int::enableExternalInterrupt();
//	lis3::Int::enableExternalInterruptVector(12);

	lis3::Cs::setOutput(xpcc::Gpio::High);

	lis3::Sck::connect(lis3::SpiMaster::Sck);
	lis3::Mosi::connect(lis3::SpiMaster::Mosi);
	lis3::Miso::connect(lis3::SpiMaster::Miso);

	lis3::SpiMaster::initialize<systemClock, MHz10>();
	lis3::SpiMaster::setDataMode(lis3::SpiMaster::DataMode::Mode3);
}

/// not supported yet, due to missing I2S driver
inline void
initializeCs43()
{
//	cs43::Lrck::connect(cs43::I2sMaster::Ws);
//	cs43::Mclk::connect(cs43::I2sMaster::Mck);
//	cs43::Sclk::connect(cs43::I2sMaster::Ck);
//	cs43::Sdin::connect(cs43::I2sMaster::Sd);

	cs43::Reset::setOutput(xpcc::Gpio::High);

	cs43::Scl::connect(cs43::I2cMaster::Scl);
	cs43::Sda::connect(cs43::I2cMaster::Sda);
	cs43::I2cMaster::initialize<systemClock, cs43::I2cMaster::Baudrate::Standard>();
}

/// not supported yet, due to missing I2S driver
inline void
initializeMp45()
{
//	mp45::Clk::connect(mp45::I2sMaster::Ck);
//	mp45::Dout::connect(mp45::I2sMaster::Sd);
}

/// not supported yet, due to missing USB driver
inline void
initializeUsb()
{
//	usb::Dm::connect(usb::Device::Dm);
//	usb::Dp::connect(usb::Device::Dp);
//	usb::Id::connect(usb::Device::Id);

	usb::Power::setOutput(Gpio::OutputType::PushPull, Gpio::OutputSpeed::MHz2);

	usb::Overcurrent::setInput(Gpio::InputType::Floating);
	usb::VBus::setInput(Gpio::InputType::Floating);
}

}

#endif	// XPCC_STM32_F4_DISCOVERY_HPP
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_get_poundv_bucket_attr.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_pm_get_poundv_bucket_attr.C
/// @brief Grab PM data from certain bucket in #V keyword in LRPX record
///

// ----------------------------------------------------------------------
// Includes
// ----------------------------------------------------------------------
#include <p9_pm_get_poundv_bucket_attr.H>
#include <p9_pm_get_poundv_bucket.H>
#include <mvpd_access_defs.H>
#include <attribute_ids.H>

fapi2::ReturnCode p9_pm_get_poundv_bucket_attr(
    const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,
    uint8_t* o_data)
{
    FAPI_DBG("Entering p9_pm_get_poundv_bucket_attr ....");
    uint8_t* l_prDataPtr = NULL;
    uint8_t* l_fullVpdData = NULL;
    uint8_t l_overridePresent = 0;
    uint32_t l_tempVpdSize = 0;
    uint32_t l_vpdSize = 0;
    uint8_t l_eqChipUnitPos = 0;
    uint8_t l_bucketId;
    uint8_t l_bucketSize = 0;
    uint32_t l_sysNestFreq = 0;
    fapi2::voltageBucketData_t* l_currentBucket = NULL;
    uint8_t l_numMatches = 0;

    fapi2::MvpdRecord lrpRecord = fapi2::MVPD_RECORD_LAST;
    //To read MVPD we will need the proc parent of the inputted EQ target
    fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_procParent =
        i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();

    //Need to determine which LRP record to read from depending on which
    //bucket we are getting the power management data from. FapiPos will
    //tell us which LRP record to use.
    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS,
                           i_target,
                           l_eqChipUnitPos));

    FAPI_ASSERT( l_eqChipUnitPos < NUM_BUCKETS ,
                 fapi2::INVALID_EQ_CHIP_POS().
                 set_EQ_POSITION( l_eqChipUnitPos ),
                 "Invalid EQ chip unit position = 0x%X",
                 l_eqChipUnitPos);

    //The enumeration for the LRPx records are just 3 more
    //than the EQ chip unit pos. See mvpd_access_defs.H
    lrpRecord = static_cast<fapi2::MvpdRecord>(l_eqChipUnitPos +
                fapi2::MVPD_RECORD_LRP0 );

    //check if bucket num has been overriden
    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM_OVERRIDE,
                           i_target,
                           l_overridePresent));

    if(l_overridePresent != 0)
    {
        //If it has been overriden then get the override
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM,
                               i_target,
                               l_bucketId));
    }
    else
    {
        //First read is to get size of vpd record, note the o_buffer is NULL
        FAPI_TRY( getMvpdField(lrpRecord,
                               fapi2::MVPD_KEYWORD_PDV,
                               l_procParent,
                               NULL,
                               l_tempVpdSize) );

        //save off the actual vpd size
        l_vpdSize = l_tempVpdSize;
        //Allocate memory for vpd data
        l_fullVpdData = reinterpret_cast<uint8_t*>(malloc(l_tempVpdSize));

        //Second read is to get data of vpd record
        FAPI_TRY( getMvpdField(lrpRecord,
                               fapi2::MVPD_KEYWORD_PDV,
                               l_procParent,
                               l_fullVpdData,
                               l_tempVpdSize) );

        //Version 2:
        //#V record is laid out as follows:
        //Name:     0x2 byte
        //Length:   0x2 byte
        //Version:  0x1 byte **buffer starts here
        //PNP:      0x3 byte
        //bucket a: 0x33 byte
        //bucket b: 0x33 byte
        //bucket c: 0x33 byte
        //bucket d: 0x33 byte
        //bucket e: 0x33 byte
        //bucket f: 0x33 byte
        if( *l_fullVpdData == POUNDV_VERSION_2)
        {
            //Set the size of the bucket
            l_bucketSize = VERSION_2_BUCKET_SIZE;

            //Reset VPD size because we want to find size of another VPD record
            l_tempVpdSize = 0;

            //First read is to get size of vpd record, note the o_buffer is NULL
            FAPI_TRY( getMvpdField(fapi2::MVPD_RECORD_VINI,
                                   fapi2::MVPD_KEYWORD_PR,
                                   l_procParent,
                                   NULL,
                                   l_tempVpdSize) );

            l_prDataPtr = reinterpret_cast<uint8_t*>(malloc(l_tempVpdSize));

            //Second read is to get data of vpd record
            FAPI_TRY( getMvpdField(fapi2::MVPD_RECORD_VINI,
                                   fapi2::MVPD_KEYWORD_PR,
                                   l_procParent,
                                   l_prDataPtr,
                                   l_tempVpdSize) );

            //Bucket ID is byte[4] of the PR keyword
            memcpy(&l_bucketId, (l_prDataPtr + 4), sizeof(uint8_t));

        }
        //Version 3:
        //#V record is laid out as follows:
        //Name:     0x2 byte
        //Length:   0x2 byte
        //Version:  0x1 byte **buffer starts here
        //PNP:      0x3 byte
        //bucket a: 0x3D byte
        //bucket b: 0x3D byte
        //bucket c: 0x3D byte
        //bucket d: 0x3D byte
        //bucket e: 0x3D byte
        //bucket f: 0x3D byte
        else if( *l_fullVpdData == POUNDV_VERSION_3 )
        {
            // Set the size of the bucket
            l_bucketSize = VERSION_3_BUCKET_SIZE;

            // Version 3 uses the nest frequency to choose the bucket Id
            // get the system target to find the NEST_FREQ_MHZ
            fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> l_sysParent;

            FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_PB_MHZ,
                                   l_sysParent,
                                   l_sysNestFreq));
            //cast the voltage data into an array of buckets
            fapi2::voltageBucketData_t* l_buckets = reinterpret_cast
                                                    <fapi2::voltageBucketData_t*>
                                                    (l_fullVpdData + POUNDV_BUCKET_OFFSET);

            for(int i = 0; i < NUM_BUCKETS; i++)
            {
                if(l_buckets[i].pbFreq == l_sysNestFreq)
                {
                    l_numMatches++;

                    /*
                     * TODO RTC: 157341
                     * Modify function to fail if multiple buckets have same nest
                     */
                    if(l_numMatches > 1)
                    {
                        FAPI_ERR("p9_pm_get_poundv_bucket_attr::"
                                 " Multiple buckets (%d) reporting the same nest frequency",
                                 l_numMatches);
                    }

                    /*
                    else
                    {
                        l_currentBucket = &l_buckets[i];
                    }
                    */
                    l_currentBucket = &l_buckets[i];
                }
            }

            /*
             * TODO RTC: 157341
             * Modify function to fail if multiple buckets have same nest
             if(l_numMatches == 1)
             {
                 l_bucketId = l_currentBucket->bucketId;
             }
             else
             {

                 FAPI_ERR("p9_pm_get_poundv_bucket_attr::Invalid number of matching nest freqs found. Matches found = %d",
                          l_numMatches );
                 FAPI_ASSERT(0,
                             fapi2::INVALID_MATCHING_FREQ_NUMBER().
                             set_MATCHES_FOUND(l_numMatches),
                             "Matches found is NOT 1" );
             }
             */
            l_bucketId = l_currentBucket->bucketId;
        }
        else
        {
            FAPI_ASSERT( false,
                         fapi2::INVALID_POUNDV_VERSION()
                         .set_POUNDV_VERSION(*l_fullVpdData),
                         "p9_pm_get_poundv_bucket_attr::Invalid #V record version: 0x%x",
                         *l_fullVpdData);
        }

        // This assert ensures the size of the calculated data is correct
        FAPI_ASSERT(l_vpdSize - POUNDV_BUCKET_OFFSET - ((l_bucketId - 1) *
                    l_bucketSize) >= l_bucketSize,
                    fapi2::BAD_VPD_READ().set_EXPECTED_SIZE(sizeof(l_bucketSize))
                    .set_ACTUAL_SIZE(l_vpdSize - POUNDV_BUCKET_OFFSET -
                                     ((l_bucketId - 1) * l_bucketSize)),
                    "#V data read was too small!" );

    }// else no override

    // Ensure we got a valid bucket id
    // NOTE: Bucket IDs range from 1-6
    FAPI_ASSERT( (l_bucketId <= NUM_BUCKETS) && (l_bucketId != 0),
                 fapi2::INVALID_BUCKET_ID()
                 .set_TARGET(i_target)
                 .set_BUCKET_ID(l_bucketId),
                 "Invalid Bucket Id = %d",
                 l_bucketId );

    // Use the selected bucket id to populate the output data
    memcpy(o_data,
           l_fullVpdData + POUNDV_BUCKET_OFFSET + (l_bucketId - 1) * l_bucketSize,
           l_bucketSize);

fapi_try_exit:

    if(l_fullVpdData != NULL)
    {
        free(l_fullVpdData);
        l_fullVpdData = NULL;
    }

    if(l_prDataPtr != NULL)
    {
        free(l_prDataPtr);
        l_prDataPtr = NULL;
    }

    FAPI_DBG("Exiting p9_pm_get_poundv_bucket_attr ....");

    return fapi2::current_err;
}
<commit_msg>Modify #V accessor to fail if multiple buckets report same nest<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_get_poundv_bucket_attr.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_pm_get_poundv_bucket_attr.C
/// @brief Grab PM data from certain bucket in #V keyword in LRPX record
///

// ----------------------------------------------------------------------
// Includes
// ----------------------------------------------------------------------
#include <p9_pm_get_poundv_bucket_attr.H>
#include <p9_pm_get_poundv_bucket.H>
#include <mvpd_access_defs.H>
#include <attribute_ids.H>

fapi2::ReturnCode p9_pm_get_poundv_bucket_attr(
    const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,
    uint8_t* o_data)
{
    FAPI_DBG("Entering p9_pm_get_poundv_bucket_attr ....");
    uint8_t* l_prDataPtr = NULL;
    uint8_t* l_fullVpdData = NULL;
    uint8_t l_overridePresent = 0;
    uint32_t l_tempVpdSize = 0;
    uint32_t l_vpdSize = 0;
    uint8_t l_eqChipUnitPos = 0;
    uint8_t l_bucketId;
    uint8_t l_bucketSize = 0;
    uint32_t l_sysNestFreq = 0;
    fapi2::voltageBucketData_t* l_currentBucket = NULL;
    uint8_t l_numMatches = 0;

    fapi2::MvpdRecord lrpRecord = fapi2::MVPD_RECORD_LAST;
    //To read MVPD we will need the proc parent of the inputted EQ target
    fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_procParent =
        i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();

    //Need to determine which LRP record to read from depending on which
    //bucket we are getting the power management data from. FapiPos will
    //tell us which LRP record to use.
    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS,
                           i_target,
                           l_eqChipUnitPos));

    FAPI_ASSERT( l_eqChipUnitPos < NUM_BUCKETS ,
                 fapi2::INVALID_EQ_CHIP_POS().
                 set_EQ_POSITION( l_eqChipUnitPos ),
                 "Invalid EQ chip unit position = 0x%X",
                 l_eqChipUnitPos);

    //The enumeration for the LRPx records are just 3 more
    //than the EQ chip unit pos. See mvpd_access_defs.H
    lrpRecord = static_cast<fapi2::MvpdRecord>(l_eqChipUnitPos +
                fapi2::MVPD_RECORD_LRP0 );

    //check if bucket num has been overriden
    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM_OVERRIDE,
                           i_target,
                           l_overridePresent));

    if(l_overridePresent != 0)
    {
        //If it has been overriden then get the override
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM,
                               i_target,
                               l_bucketId));
    }
    else
    {
        //First read is to get size of vpd record, note the o_buffer is NULL
        FAPI_TRY( getMvpdField(lrpRecord,
                               fapi2::MVPD_KEYWORD_PDV,
                               l_procParent,
                               NULL,
                               l_tempVpdSize) );

        //save off the actual vpd size
        l_vpdSize = l_tempVpdSize;
        //Allocate memory for vpd data
        l_fullVpdData = reinterpret_cast<uint8_t*>(malloc(l_tempVpdSize));

        //Second read is to get data of vpd record
        FAPI_TRY( getMvpdField(lrpRecord,
                               fapi2::MVPD_KEYWORD_PDV,
                               l_procParent,
                               l_fullVpdData,
                               l_tempVpdSize) );

        //Version 2:
        //#V record is laid out as follows:
        //Name:     0x2 byte
        //Length:   0x2 byte
        //Version:  0x1 byte **buffer starts here
        //PNP:      0x3 byte
        //bucket a: 0x33 byte
        //bucket b: 0x33 byte
        //bucket c: 0x33 byte
        //bucket d: 0x33 byte
        //bucket e: 0x33 byte
        //bucket f: 0x33 byte
        if( *l_fullVpdData == POUNDV_VERSION_2)
        {
            //Set the size of the bucket
            l_bucketSize = VERSION_2_BUCKET_SIZE;

            //Reset VPD size because we want to find size of another VPD record
            l_tempVpdSize = 0;

            //First read is to get size of vpd record, note the o_buffer is NULL
            FAPI_TRY( getMvpdField(fapi2::MVPD_RECORD_VINI,
                                   fapi2::MVPD_KEYWORD_PR,
                                   l_procParent,
                                   NULL,
                                   l_tempVpdSize) );

            l_prDataPtr = reinterpret_cast<uint8_t*>(malloc(l_tempVpdSize));

            //Second read is to get data of vpd record
            FAPI_TRY( getMvpdField(fapi2::MVPD_RECORD_VINI,
                                   fapi2::MVPD_KEYWORD_PR,
                                   l_procParent,
                                   l_prDataPtr,
                                   l_tempVpdSize) );

            //Bucket ID is byte[4] of the PR keyword
            memcpy(&l_bucketId, (l_prDataPtr + 4), sizeof(uint8_t));

        }
        //Version 3:
        //#V record is laid out as follows:
        //Name:     0x2 byte
        //Length:   0x2 byte
        //Version:  0x1 byte **buffer starts here
        //PNP:      0x3 byte
        //bucket a: 0x3D byte
        //bucket b: 0x3D byte
        //bucket c: 0x3D byte
        //bucket d: 0x3D byte
        //bucket e: 0x3D byte
        //bucket f: 0x3D byte
        else if( *l_fullVpdData == POUNDV_VERSION_3 )
        {
            // Set the size of the bucket
            l_bucketSize = VERSION_3_BUCKET_SIZE;

            // Version 3 uses the nest frequency to choose the bucket Id
            // get the system target to find the NEST_FREQ_MHZ
            fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> l_sysParent;

            FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_PB_MHZ,
                                   l_sysParent,
                                   l_sysNestFreq));
            //cast the voltage data into an array of buckets
            fapi2::voltageBucketData_t* l_buckets = reinterpret_cast
                                                    <fapi2::voltageBucketData_t*>
                                                    (l_fullVpdData + POUNDV_BUCKET_OFFSET);

            for(int i = 0; i < NUM_BUCKETS; i++)
            {
                if(l_buckets[i].pbFreq == l_sysNestFreq)
                {
                    l_numMatches++;

                    if(l_numMatches > 1)
                    {
                        FAPI_ERR("p9_pm_get_poundv_bucket_attr::"
                                 " Multiple buckets (%d) reporting the same nest frequency"
                                 " Bucket Nest = %d Bucket ID = %d",
                                 l_numMatches,
                                 l_buckets[i].pbFreq,
                                 (i + 1));

                    }
                    else
                    {
                        l_currentBucket = &l_buckets[i];
                    }
                }
            }

            if(l_numMatches == 1)
            {
                l_bucketId = l_currentBucket->bucketId;
            }
            else
            {

                FAPI_ERR("p9_pm_get_poundv_bucket_attr::Invalid number of matching nest freqs found. Matches found = %d",
                         l_numMatches );
                FAPI_ASSERT(false,
                            fapi2::INVALID_MATCHING_FREQ_NUMBER().
                            set_MATCHES_FOUND(l_numMatches),
                            "Matches found is NOT 1" );
            }
        }
        else
        {
            FAPI_ASSERT( false,
                         fapi2::INVALID_POUNDV_VERSION()
                         .set_POUNDV_VERSION(*l_fullVpdData),
                         "p9_pm_get_poundv_bucket_attr::Invalid #V record version: 0x%x",
                         *l_fullVpdData);
        }

        // This assert ensures the size of the calculated data is correct
        FAPI_ASSERT(l_vpdSize - POUNDV_BUCKET_OFFSET - ((l_bucketId - 1) *
                    l_bucketSize) >= l_bucketSize,
                    fapi2::BAD_VPD_READ().set_EXPECTED_SIZE(sizeof(l_bucketSize))
                    .set_ACTUAL_SIZE(l_vpdSize - POUNDV_BUCKET_OFFSET -
                                     ((l_bucketId - 1) * l_bucketSize)),
                    "#V data read was too small!" );

    }// else no override

    // Ensure we got a valid bucket id
    // NOTE: Bucket IDs range from 1-6
    FAPI_ASSERT( (l_bucketId <= NUM_BUCKETS) && (l_bucketId != 0),
                 fapi2::INVALID_BUCKET_ID()
                 .set_TARGET(i_target)
                 .set_BUCKET_ID(l_bucketId),
                 "Invalid Bucket Id = %d",
                 l_bucketId );

    // Use the selected bucket id to populate the output data
    memcpy(o_data,
           l_fullVpdData + POUNDV_BUCKET_OFFSET + (l_bucketId - 1) * l_bucketSize,
           l_bucketSize);

fapi_try_exit:

    if(l_fullVpdData != NULL)
    {
        free(l_fullVpdData);
        l_fullVpdData = NULL;
    }

    if(l_prDataPtr != NULL)
    {
        free(l_prDataPtr);
        l_prDataPtr = NULL;
    }

    FAPI_DBG("Exiting p9_pm_get_poundv_bucket_attr ....");

    return fapi2::current_err;
}
<|endoftext|>


<commit_before>/**
 * Zillians MMO
 * Copyright (C) 2007-2011 Zillians.com, Inc.
 * For more information see http://www.zillians.com
 *
 * Zillians MMO is the library and runtime for massive multiplayer online game
 * development in utility computing model, which runs as a service for every
 * developer to build their virtual world running on our GPU-assisted machines.
 *
 * This is a close source library intended to be used solely within Zillians.com
 *
 * 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
 * COPYRIGHT HOLDER(S) 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 "language/stage/StageConductor.h"
#include "language/logging/Logger.h"
#include "utility/TemplateTricks.h"

namespace zillians { namespace language { namespace stage {

StageConductor::StageConductor()
{ }

StageConductor::~StageConductor()
{ }

void StageConductor::appendStage(shared_ptr<Stage> stage)
{
	mStages.push_back(stage);
}

int StageConductor::main(int argc, const char** argv)
{
	// prepare simple logger appender
	if(true)
	{

	}
	else
	{
		log4cxx::BasicConfigurator::configure();
	}

	// call implementation's initialize() to append stages
	initialize();

	if(true)
	{
		po::options_description option_desc;
		po::positional_options_description positional_option_desc;
		po::variables_map vm;

		// built-in help option
	    option_desc.add_options()
	    ("help,h", "show help");

	    // ask each stage to append their option description
		foreach(stage, mStages)
			(*stage)->initializeOptions(option_desc, positional_option_desc);

		// try to parse the command line
	    try
	    {
	    	po::store(po::command_line_parser(argc, argv).options(option_desc).positional(positional_option_desc).run(), vm);
	    	po::notify(vm);
	    }
	    catch(...)
	    {
	    	std::cerr << "failed to parse command line" << std::endl;
	    	std::cerr << option_desc << std::endl;
	    	return -1;
	    }

	    // if help option is specified, print the options and exit
	    if(vm.count("help") > 0 || argc < 2)
	    {
	    	std::cout << "command line options: " << std::endl << std::endl;
	    	std::cout << option_desc << std::endl;
	    	return 0;
	    }

	    // otherwise, process the given commands through each staged execution

	    // let each stage determine what to do
		foreach(stage, mStages)
		{
			if(!(*stage)->parseOptions(vm))
			{
				std::cerr << "failed to process command option for stage: " << (*stage)->name() << std::endl;
				std::cerr << option_desc << std::endl;
				return -1;
			}
		}

		// perform the execution
		foreach(stage, mStages)
		{
			if(!(*stage)->execute())
			{
				std::cerr << "execution failed at stage: " << (*stage)->name() << std::endl;
				return -1;
			}
		}
	}

	// call implementation's finalize() to remove stages or collect summary
	finalize();

	return 0;
}

} } }
<commit_msg>initialize logger in stage conductor<commit_after>/**
 * Zillians MMO
 * Copyright (C) 2007-2011 Zillians.com, Inc.
 * For more information see http://www.zillians.com
 *
 * Zillians MMO is the library and runtime for massive multiplayer online game
 * development in utility computing model, which runs as a service for every
 * developer to build their virtual world running on our GPU-assisted machines.
 *
 * This is a close source library intended to be used solely within Zillians.com
 *
 * 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
 * COPYRIGHT HOLDER(S) 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 "language/stage/StageConductor.h"
#include "language/logging/Logger.h"
#include "utility/TemplateTricks.h"

namespace zillians { namespace language { namespace stage {

StageConductor::StageConductor()
{ }

StageConductor::~StageConductor()
{ }

void StageConductor::appendStage(shared_ptr<Stage> stage)
{
	mStages.push_back(stage);
}

int StageConductor::main(int argc, const char** argv)
{
	// prepare simple logger appender
	if(true)
	{
		Logger::initialize();
	}
	else
	{
		log4cxx::BasicConfigurator::configure();
	}

	// call implementation's initialize() to append stages
	initialize();

	if(true)
	{
		po::options_description option_desc;
		po::positional_options_description positional_option_desc;
		po::variables_map vm;

		// built-in help option
	    option_desc.add_options()
	    ("help,h", "show help");

	    // ask each stage to append their option description
		foreach(stage, mStages)
			(*stage)->initializeOptions(option_desc, positional_option_desc);

		// try to parse the command line
	    try
	    {
	    	po::store(po::command_line_parser(argc, argv).options(option_desc).positional(positional_option_desc).run(), vm);
	    	po::notify(vm);
	    }
	    catch(...)
	    {
	    	std::cerr << "failed to parse command line" << std::endl;
	    	std::cerr << option_desc << std::endl;
	    	return -1;
	    }

	    // if help option is specified, print the options and exit
	    if(vm.count("help") > 0 || argc < 2)
	    {
	    	std::cout << "command line options: " << std::endl << std::endl;
	    	std::cout << option_desc << std::endl;
	    	return 0;
	    }

	    // otherwise, process the given commands through each staged execution

	    // let each stage determine what to do
		foreach(stage, mStages)
		{
			if(!(*stage)->parseOptions(vm))
			{
				std::cerr << "failed to process command option for stage: " << (*stage)->name() << std::endl;
				std::cerr << option_desc << std::endl;
				return -1;
			}
		}

		// perform the execution
		foreach(stage, mStages)
		{
			if(!(*stage)->execute())
			{
				std::cerr << "execution failed at stage: " << (*stage)->name() << std::endl;
				return -1;
			}
		}
	}

	// call implementation's finalize() to remove stages or collect summary
	finalize();

	return 0;
}

} } }
<|endoftext|>


<commit_before>/*
 *  GameState.cpp
 *  OpenLieroX
 *
 *  Created by Albert Zeyer on 15.02.12.
 *  code under LGPL
 *
 */

#include "GameState.h"
#include "Game.h"
#include "Settings.h"
#include "CWorm.h"
#include "CBytestream.h"
#include "ClassInfo.h"
#include "ProfileSystem.h"
#include "CServerConnection.h"

ScriptVar_t ObjectState::getValue(AttribRef a) const {
	Attribs::const_iterator it = attribs.find(a);
	if(it == attribs.end())
		return a.getAttrDesc()->defaultValue;
	return it->second.value;
}

GameStateUpdates::operator bool() const {
	if(!objs.empty()) return true;
	if(!objCreations.empty()) return true;
	if(!objDeletions.empty()) return true;
	return false;
}

void GameStateUpdates::writeToBs(CBytestream* bs) const {
	bs->writeInt16((uint16_t)objCreations.size());
	foreach(o, objCreations) {
		o->writeToBs(bs);
	}

	bs->writeInt16((uint16_t)objDeletions.size());
	foreach(o, objDeletions) {
		o->writeToBs(bs);
	}

	bs->writeInt((uint32_t)objs.size(), 4);
	foreach(a, objs) {
		const ObjAttrRef& attr = *a;
		ScriptVar_t curValue = a->get();
		attr.writeToBs(bs);
		bs->writeVar(curValue);
	}
}

static BaseObject* getObjFromRef(ObjRef r) {
	switch(r.classId) {
	case LuaID<Game>::value: return &game;
	case LuaID<CWorm>::value: return game.wormById(r.objId, false);
	default: break;
	}
	return NULL;
}

static bool attrBelongsToClass(const ClassInfo* classInfo, const AttrDesc* attrDesc) {
	return classInfo->isTypeOf(attrDesc->objTypeId);
}

static bool ownObject(ObjRef o) {
	// This is very custom right now and need to be made somewhat more general.
	if(o.classId == LuaID<CWorm>::value) {
		CWorm* w = game.wormById(o.objId, false);
		if(!w) return false;
		return w->getLocal();
	}
	if(game.isServer()) return true;
	return false;
}

// This only make sense as server.
static bool ownObject(CServerConnection* source, ObjRef o) {
	assert(game.isServer());
	// This is very custom right now and need to be made somewhat more general.
	if(o.classId == LuaID<CWorm>::value) {
		return source->OwnsWorm(o.objId);
	}
	return false;
}

void GameStateUpdates::handleFromBs(CBytestream* bs, CServerConnection* source) {
	if(game.isServer()) {
		assert(source != NULL);
		if(source->isLocalClient()) {
			// This shouldn't happen. It means sth in our server connection list is messed up.
			errors << "GameStateUpdates::handleFromBs as server from local client" << endl;
			bs->SkipAll();
			return;
		}
	}
	else
		assert(source == NULL);

	uint16_t creationsNum = bs->readInt16();
	for(uint16_t i = 0; i < creationsNum; ++i) {
		ObjRef r;
		r.readFromBs(bs);
		//BaseObject* o = getClassInfo(r.classId)->createInstance();
		//o->thisRef.classId = r.classId;
		//o->thisRef.objId = r.objId;

		// we only handle/support CWorm objects for now...
		if(game.isServer()) {
			errors << "GameStateUpdates::handleFromBs: got obj creation as server: " << r.description() << endl;
			bs->SkipAll();
			return;
		}
		if(r.classId != LuaID<CWorm>::value) {
			errors << "GameStateUpdates::handleFromBs: obj-creation: invalid class: " << r.description() << endl;
			bs->SkipAll();
			return;
		}
		if(game.wormById(r.objId, false) != NULL) {
			errors << "GameStateUpdates::handleFromBs: worm-creation: worm " << r.objId << " already exists" << endl;
			bs->SkipAll();
			return;
		}
		game.createNewWorm(r.objId, false, NULL, Version());
	}

	uint16_t deletionsNum = bs->readInt16();
	for(uint16_t i = 0; i < deletionsNum; ++i) {
		ObjRef r;
		r.readFromBs(bs);

		// we only handle/support CWorm objects for now...
		if(game.isServer()) {
			errors << "GameStateUpdates::handleFromBs: got obj deletion as server: " << r.description() << endl;
			bs->SkipAll();
			return;
		}
		if(r.classId != LuaID<CWorm>::value) {
			errors << "GameStateUpdates::handleFromBs: obj-deletion: invalid class: " << r.description() << endl;
			bs->SkipAll();
			return;
		}
		CWorm* w = game.wormById(r.objId, false);
		if(!w) {
			errors << "GameStateUpdates::handleFromBs: obj-deletion: worm " << r.objId << " does not exist" << endl;
			bs->SkipAll();
			return;
		}
		game.removeWorm(w);
	}

	uint32_t attrUpdatesNum = bs->readInt(4);
	for(uint32_t i = 0; i < attrUpdatesNum; ++i) {
		ObjAttrRef r;
		r.readFromBs(bs);

		const AttrDesc* attrDesc = r.attr.getAttrDesc();
		if(attrDesc == NULL) {
			errors << "GameStateUpdates::handleFromBs: AttrDesc for update not found" << endl;
			bs->SkipAll();
			return;
		}

		const ClassInfo* classInfo = getClassInfo(r.obj.classId);
		if(classInfo == NULL) {
			errors << "GameStateUpdates::handleFromBs: class " << r.obj.classId << " for obj-update unknown" << endl;
			bs->SkipAll();
			return;
		}

		if(!attrBelongsToClass(classInfo, attrDesc)) {
			errors << "GameStateUpdates::handleFromBs: attr " << attrDesc->description() << " does not belong to class " << r.obj.classId << " for obj-update" << endl;
			bs->SkipAll();
			return;
		}

		// see GameStateUpdates::diffFromStateToCurrent for the other side
		if(attrDesc->serverside) {
			if(game.isServer()) {
				errors << "GameStateUpdates::handleFromBs: got serverside attr update as server: " << r.description() << endl;
				bs->SkipAll();
				return;
			}
		}
		else { // client-side attr
			if(game.isServer() && !ownObject(source, r.obj)) {
				errors << "GameStateUpdates::handleFromBs: got update from not-authorized client " << source->debugName() << ": " << r.description() << endl;
				bs->SkipAll();
				return;
			}
		}

		ScriptVar_t v;
		bs->readVar(v);

		// for now, this is somewhat specific to the only types we support
		if(r.obj.classId == LuaID<Settings>::value) {
			if(game.isServer()) {
				errors << "GameStateUpdates::handleFromBs: got settings update as server" << endl;
				bs->SkipAll();
				return;
			}
			if(!Settings::getAttrDescs().belongsToUs(attrDesc)) {
				errors << "GameStateUpdates::handleFromBs: settings update AttrDesc " << attrDesc->description() << " is not a setting attr" << endl;
				bs->SkipAll();
				return;
			}
			FeatureIndex fIndex = Settings::getAttrDescs().getIndex(attrDesc);
			cClient->getGameLobby().overwrite[fIndex] = v;
		}
		else {
			BaseObject* o = getObjFromRef(r.obj);
			if(o == NULL) {
				errors << "GameStateUpdates::handleFromBs: object for attr update not found: " << r.description() << endl;
				bs->SkipAll();
				return;
			}
			if(o->thisRef != r.obj) {
				errors << "GameStateUpdates::handleFromBs: object-ref for attr update invalid: " << r.description() << endl;
				bs->SkipAll();
				return;
			}
			if(attrDesc == game.state.attrDesc()) {
				if((int)v == Game::S_Quit) {
					notes << "GameStateUpdates: server quitted OLX, we just go to inactive" << endl;
					v = Game::S_Inactive;
				}
			}
			attrDesc->set(o, v, true);
		}

		//notes << "game state update: <" << r.obj.description() << "> " << attrDesc->attrName << " to " << v.toString() << endl;
	}
}

void GameStateUpdates::pushObjAttrUpdate(ObjAttrRef a) {
	objs.insert(a);
}

void GameStateUpdates::pushObjCreation(ObjRef o) {
	objDeletions.erase(o);
	objCreations.insert(o);
}

void GameStateUpdates::pushObjDeletion(ObjRef o) {
	Objs::iterator itStart = objs.lower_bound(ObjAttrRef::LowerLimit(o));
	Objs::iterator itEnd = objs.upper_bound(ObjAttrRef::UpperLimit(o));
	objs.erase(itStart, itEnd);
	objCreations.erase(o);
	objDeletions.insert(o);
}

void GameStateUpdates::reset() {
	objs.clear();
	objCreations.clear();
	objDeletions.clear();
}

void GameStateUpdates::diffFromStateToCurrent(const GameState& s) {
	reset();
	foreach(o, game.gameStateUpdates->objCreations) {
		if(game.isClient()) continue; // none-at-all right now... worm-creation is handled independently atm
		if(!ownObject(*o)) continue;
		if(!s.haveObject(*o))
			pushObjCreation(*o);
	}
	foreach(u, game.gameStateUpdates->objs) {
		if(!ownObject(u->obj)) continue;
		const AttrDesc* attrDesc = u->attr.getAttrDesc();
		if(attrDesc->serverside) {
			if(game.isClient()) continue;
		}
		else { // non serverside attr
			if(game.isClient() && !ownObject(u->obj)) continue;
		}
		ScriptVar_t curValue = u->get();
		ScriptVar_t stateValue = attrDesc->defaultValue;
		if(s.haveObject(u->obj))
			stateValue = s.getValue(*u);
		//notes << "update " << u->description() << ": " << curValue.toString() << " -> " << stateValue.toString() << endl;
		if(curValue != stateValue)
			pushObjAttrUpdate(*u);
	}
	foreach(o, game.gameStateUpdates->objDeletions) {
		if(game.isClient()) continue; // see obj-creations
		if(!ownObject(*o)) continue;
		if(s.haveObject(*o))
			pushObjDeletion(*o);
	}
}

static ObjectState& GameState_registerObj(GameState& s, BaseObject* obj) {
	return s.objs[obj->thisRef] = ObjectState(obj);
}

GameState::GameState() {
	// register singletons which are always there
	GameState_registerObj(*this, &game);
	GameState_registerObj(*this, &gameSettings);
}

GameState GameState::Current() {
	GameState s;
	s.updateToCurrent();
	return s;
}

void GameState::reset() {
	*this = GameState();
}

void GameState::updateToCurrent() {
	reset();
	foreach(o, game.gameStateUpdates->objCreations) {
		objs[*o] = ObjectState(*o);
	}
	foreach(u, game.gameStateUpdates->objs) {
		ObjAttrRef r = *u;
		Objs::iterator it = objs.find(r.obj);
		assert(it != objs.end());
		ObjectState& s = it->second;
		assert(s.obj == it->first);
		s.attribs[u->attr].value = r.get();
	}
}

void GameState::addObject(ObjRef o) {
	assert(!haveObject(o));
	objs[o] = ObjectState(o);
}

bool GameState::haveObject(ObjRef o) const {
	Objs::const_iterator it = objs.find(o);
	return it != objs.end();
}

ScriptVar_t GameState::getValue(ObjAttrRef a) const {
	Objs::const_iterator it = objs.find(a.obj);
	assert(it != objs.end());
	assert(it->second.obj == a.obj);
	return it->second.getValue(a.attr);
}

<commit_msg>fix for game.state client-side update<commit_after>/*
 *  GameState.cpp
 *  OpenLieroX
 *
 *  Created by Albert Zeyer on 15.02.12.
 *  code under LGPL
 *
 */

#include "GameState.h"
#include "Game.h"
#include "Settings.h"
#include "CWorm.h"
#include "CBytestream.h"
#include "ClassInfo.h"
#include "ProfileSystem.h"
#include "CServerConnection.h"

ScriptVar_t ObjectState::getValue(AttribRef a) const {
	Attribs::const_iterator it = attribs.find(a);
	if(it == attribs.end())
		return a.getAttrDesc()->defaultValue;
	return it->second.value;
}

GameStateUpdates::operator bool() const {
	if(!objs.empty()) return true;
	if(!objCreations.empty()) return true;
	if(!objDeletions.empty()) return true;
	return false;
}

void GameStateUpdates::writeToBs(CBytestream* bs) const {
	bs->writeInt16((uint16_t)objCreations.size());
	foreach(o, objCreations) {
		o->writeToBs(bs);
	}

	bs->writeInt16((uint16_t)objDeletions.size());
	foreach(o, objDeletions) {
		o->writeToBs(bs);
	}

	bs->writeInt((uint32_t)objs.size(), 4);
	foreach(a, objs) {
		const ObjAttrRef& attr = *a;
		ScriptVar_t curValue = a->get();
		attr.writeToBs(bs);
		bs->writeVar(curValue);
	}
}

static BaseObject* getObjFromRef(ObjRef r) {
	switch(r.classId) {
	case LuaID<Game>::value: return &game;
	case LuaID<CWorm>::value: return game.wormById(r.objId, false);
	default: break;
	}
	return NULL;
}

static bool attrBelongsToClass(const ClassInfo* classInfo, const AttrDesc* attrDesc) {
	return classInfo->isTypeOf(attrDesc->objTypeId);
}

static bool ownObject(ObjRef o) {
	// This is very custom right now and need to be made somewhat more general.
	if(o.classId == LuaID<CWorm>::value) {
		CWorm* w = game.wormById(o.objId, false);
		if(!w) return false;
		return w->getLocal();
	}
	if(game.isServer()) return true;
	return false;
}

// This only make sense as server.
static bool ownObject(CServerConnection* source, ObjRef o) {
	assert(game.isServer());
	// This is very custom right now and need to be made somewhat more general.
	if(o.classId == LuaID<CWorm>::value) {
		return source->OwnsWorm(o.objId);
	}
	return false;
}

void GameStateUpdates::handleFromBs(CBytestream* bs, CServerConnection* source) {
	if(game.isServer()) {
		assert(source != NULL);
		if(source->isLocalClient()) {
			// This shouldn't happen. It means sth in our server connection list is messed up.
			errors << "GameStateUpdates::handleFromBs as server from local client" << endl;
			bs->SkipAll();
			return;
		}
	}
	else
		assert(source == NULL);

	uint16_t creationsNum = bs->readInt16();
	for(uint16_t i = 0; i < creationsNum; ++i) {
		ObjRef r;
		r.readFromBs(bs);
		//BaseObject* o = getClassInfo(r.classId)->createInstance();
		//o->thisRef.classId = r.classId;
		//o->thisRef.objId = r.objId;

		// we only handle/support CWorm objects for now...
		if(game.isServer()) {
			errors << "GameStateUpdates::handleFromBs: got obj creation as server: " << r.description() << endl;
			bs->SkipAll();
			return;
		}
		if(r.classId != LuaID<CWorm>::value) {
			errors << "GameStateUpdates::handleFromBs: obj-creation: invalid class: " << r.description() << endl;
			bs->SkipAll();
			return;
		}
		if(game.wormById(r.objId, false) != NULL) {
			errors << "GameStateUpdates::handleFromBs: worm-creation: worm " << r.objId << " already exists" << endl;
			bs->SkipAll();
			return;
		}
		game.createNewWorm(r.objId, false, NULL, Version());
	}

	uint16_t deletionsNum = bs->readInt16();
	for(uint16_t i = 0; i < deletionsNum; ++i) {
		ObjRef r;
		r.readFromBs(bs);

		// we only handle/support CWorm objects for now...
		if(game.isServer()) {
			errors << "GameStateUpdates::handleFromBs: got obj deletion as server: " << r.description() << endl;
			bs->SkipAll();
			return;
		}
		if(r.classId != LuaID<CWorm>::value) {
			errors << "GameStateUpdates::handleFromBs: obj-deletion: invalid class: " << r.description() << endl;
			bs->SkipAll();
			return;
		}
		CWorm* w = game.wormById(r.objId, false);
		if(!w) {
			errors << "GameStateUpdates::handleFromBs: obj-deletion: worm " << r.objId << " does not exist" << endl;
			bs->SkipAll();
			return;
		}
		game.removeWorm(w);
	}

	uint32_t attrUpdatesNum = bs->readInt(4);
	for(uint32_t i = 0; i < attrUpdatesNum; ++i) {
		ObjAttrRef r;
		r.readFromBs(bs);

		const AttrDesc* attrDesc = r.attr.getAttrDesc();
		if(attrDesc == NULL) {
			errors << "GameStateUpdates::handleFromBs: AttrDesc for update not found" << endl;
			bs->SkipAll();
			return;
		}

		const ClassInfo* classInfo = getClassInfo(r.obj.classId);
		if(classInfo == NULL) {
			errors << "GameStateUpdates::handleFromBs: class " << r.obj.classId << " for obj-update unknown" << endl;
			bs->SkipAll();
			return;
		}

		if(!attrBelongsToClass(classInfo, attrDesc)) {
			errors << "GameStateUpdates::handleFromBs: attr " << attrDesc->description() << " does not belong to class " << r.obj.classId << " for obj-update" << endl;
			bs->SkipAll();
			return;
		}

		// see GameStateUpdates::diffFromStateToCurrent for the other side
		if(attrDesc->serverside) {
			if(game.isServer()) {
				errors << "GameStateUpdates::handleFromBs: got serverside attr update as server: " << r.description() << endl;
				bs->SkipAll();
				return;
			}
		}
		else { // client-side attr
			if(game.isServer() && !ownObject(source, r.obj)) {
				errors << "GameStateUpdates::handleFromBs: got update from not-authorized client " << source->debugName() << ": " << r.description() << endl;
				bs->SkipAll();
				return;
			}
		}

		ScriptVar_t v;
		bs->readVar(v);

		// for now, this is somewhat specific to the only types we support
		if(r.obj.classId == LuaID<Settings>::value) {
			if(game.isServer()) {
				errors << "GameStateUpdates::handleFromBs: got settings update as server" << endl;
				bs->SkipAll();
				return;
			}
			if(!Settings::getAttrDescs().belongsToUs(attrDesc)) {
				errors << "GameStateUpdates::handleFromBs: settings update AttrDesc " << attrDesc->description() << " is not a setting attr" << endl;
				bs->SkipAll();
				return;
			}
			FeatureIndex fIndex = Settings::getAttrDescs().getIndex(attrDesc);
			cClient->getGameLobby().overwrite[fIndex] = v;
		}
		else {
			BaseObject* o = getObjFromRef(r.obj);
			if(o == NULL) {
				errors << "GameStateUpdates::handleFromBs: object for attr update not found: " << r.description() << endl;
				bs->SkipAll();
				return;
			}
			if(o->thisRef != r.obj) {
				errors << "GameStateUpdates::handleFromBs: object-ref for attr update invalid: " << r.description() << endl;
				bs->SkipAll();
				return;
			}
			if(attrDesc == game.state.attrDesc()) {
				if((int)v < Game::S_Lobby) {
					notes << "GameStateUpdates: server changed to " << Game::StateAsStr(v) << ", we wait for drop/leaving package" << endl;
					//v = Game::S_Inactive;
					continue;
				}
			}
			attrDesc->set(o, v, true);
		}

		//notes << "game state update: <" << r.obj.description() << "> " << attrDesc->attrName << " to " << v.toString() << endl;
	}
}

void GameStateUpdates::pushObjAttrUpdate(ObjAttrRef a) {
	objs.insert(a);
}

void GameStateUpdates::pushObjCreation(ObjRef o) {
	objDeletions.erase(o);
	objCreations.insert(o);
}

void GameStateUpdates::pushObjDeletion(ObjRef o) {
	Objs::iterator itStart = objs.lower_bound(ObjAttrRef::LowerLimit(o));
	Objs::iterator itEnd = objs.upper_bound(ObjAttrRef::UpperLimit(o));
	objs.erase(itStart, itEnd);
	objCreations.erase(o);
	objDeletions.insert(o);
}

void GameStateUpdates::reset() {
	objs.clear();
	objCreations.clear();
	objDeletions.clear();
}

void GameStateUpdates::diffFromStateToCurrent(const GameState& s) {
	reset();
	foreach(o, game.gameStateUpdates->objCreations) {
		if(game.isClient()) continue; // none-at-all right now... worm-creation is handled independently atm
		if(!ownObject(*o)) continue;
		if(!s.haveObject(*o))
			pushObjCreation(*o);
	}
	foreach(u, game.gameStateUpdates->objs) {
		if(!ownObject(u->obj)) continue;
		const AttrDesc* attrDesc = u->attr.getAttrDesc();
		if(attrDesc->serverside) {
			if(game.isClient()) continue;
		}
		else { // non serverside attr
			if(game.isClient() && !ownObject(u->obj)) continue;
		}
		ScriptVar_t curValue = u->get();
		ScriptVar_t stateValue = attrDesc->defaultValue;
		if(s.haveObject(u->obj))
			stateValue = s.getValue(*u);
		//notes << "update " << u->description() << ": " << curValue.toString() << " -> " << stateValue.toString() << endl;
		if(curValue != stateValue)
			pushObjAttrUpdate(*u);
	}
	foreach(o, game.gameStateUpdates->objDeletions) {
		if(game.isClient()) continue; // see obj-creations
		if(!ownObject(*o)) continue;
		if(s.haveObject(*o))
			pushObjDeletion(*o);
	}
}

static ObjectState& GameState_registerObj(GameState& s, BaseObject* obj) {
	return s.objs[obj->thisRef] = ObjectState(obj);
}

GameState::GameState() {
	// register singletons which are always there
	GameState_registerObj(*this, &game);
	GameState_registerObj(*this, &gameSettings);
}

GameState GameState::Current() {
	GameState s;
	s.updateToCurrent();
	return s;
}

void GameState::reset() {
	*this = GameState();
}

void GameState::updateToCurrent() {
	reset();
	foreach(o, game.gameStateUpdates->objCreations) {
		objs[*o] = ObjectState(*o);
	}
	foreach(u, game.gameStateUpdates->objs) {
		ObjAttrRef r = *u;
		Objs::iterator it = objs.find(r.obj);
		assert(it != objs.end());
		ObjectState& s = it->second;
		assert(s.obj == it->first);
		s.attribs[u->attr].value = r.get();
	}
}

void GameState::addObject(ObjRef o) {
	assert(!haveObject(o));
	objs[o] = ObjectState(o);
}

bool GameState::haveObject(ObjRef o) const {
	Objs::const_iterator it = objs.find(o);
	return it != objs.end();
}

ScriptVar_t GameState::getValue(ObjAttrRef a) const {
	Objs::const_iterator it = objs.find(a.obj);
	assert(it != objs.end());
	assert(it->second.obj == a.obj);
	return it->second.getValue(a.attr);
}

<|endoftext|>


<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "services/surfaces/surfaces_scheduler.h"

namespace surfaces {

SurfacesScheduler::Client::~Client() {
}

SurfacesScheduler::SurfacesScheduler(Client* client) : client_(client) {
  cc::SchedulerSettings settings;
  scheduler_ = cc::Scheduler::Create(
      this, settings, 0, base::MessageLoop::current()->task_runner(), nullptr,
      nullptr);
  scheduler_->SetCanStart();
  scheduler_->SetVisible(true);
  scheduler_->SetCanDraw(true);
}

SurfacesScheduler::~SurfacesScheduler() {
}

void SurfacesScheduler::SetNeedsDraw() {
  scheduler_->SetNeedsRedraw();
}

void SurfacesScheduler::OnVSyncParametersUpdated(base::TimeTicks timebase,
                                                 base::TimeDelta interval) {
  scheduler_->CommitVSyncParameters(timebase, interval);
}

void SurfacesScheduler::WillBeginImplFrame(const cc::BeginFrameArgs& args) {
}

void SurfacesScheduler::ScheduledActionSendBeginMainFrame() {
}

cc::DrawResult SurfacesScheduler::ScheduledActionDrawAndSwapIfPossible() {
  base::TimeTicks start = base::TimeTicks::Now();
  client_->Draw();
  base::TimeDelta duration = base::TimeTicks::Now() - start;

  draw_estimate_ = (duration + draw_estimate_) / 2;
  return cc::DRAW_SUCCESS;
}

cc::DrawResult SurfacesScheduler::ScheduledActionDrawAndSwapForced() {
  NOTREACHED() << "ScheduledActionDrawAndSwapIfPossible always succeeds.";
  return cc::DRAW_SUCCESS;
}

void SurfacesScheduler::ScheduledActionAnimate() {
}

void SurfacesScheduler::ScheduledActionCommit() {
}

void SurfacesScheduler::ScheduledActionActivateSyncTree() {
}

void SurfacesScheduler::ScheduledActionBeginOutputSurfaceCreation() {
  scheduler_->DidCreateAndInitializeOutputSurface();
}

void SurfacesScheduler::ScheduledActionPrepareTiles() {
}

void SurfacesScheduler::DidAnticipatedDrawTimeChange(base::TimeTicks time) {
}

base::TimeDelta SurfacesScheduler::DrawDurationEstimate() {
  return draw_estimate_;
}

base::TimeDelta SurfacesScheduler::BeginMainFrameToCommitDurationEstimate() {
  return base::TimeDelta();
}

base::TimeDelta SurfacesScheduler::CommitToActivateDurationEstimate() {
  return base::TimeDelta();
}

void SurfacesScheduler::DidBeginImplFrameDeadline() {
}

void SurfacesScheduler::SendBeginFramesToChildren(
    const cc::BeginFrameArgs& args) {
}

}  // namespace mojo
<commit_msg>Fix surfaces scheduler so apps can draw<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "services/surfaces/surfaces_scheduler.h"

namespace surfaces {

SurfacesScheduler::Client::~Client() {
}

SurfacesScheduler::SurfacesScheduler(Client* client) : client_(client) {
  cc::SchedulerSettings settings;
  scheduler_ = cc::Scheduler::Create(
      this, settings, 0, base::MessageLoop::current()->task_runner(), nullptr,
      nullptr);
  scheduler_->SetCanStart();
  scheduler_->SetVisible(true);
  scheduler_->SetCanDraw(true);
  scheduler_->SetNeedsCommit();
}

SurfacesScheduler::~SurfacesScheduler() {
}

void SurfacesScheduler::SetNeedsDraw() {
  scheduler_->SetNeedsRedraw();
}

void SurfacesScheduler::OnVSyncParametersUpdated(base::TimeTicks timebase,
                                                 base::TimeDelta interval) {
  scheduler_->CommitVSyncParameters(timebase, interval);
}

void SurfacesScheduler::WillBeginImplFrame(const cc::BeginFrameArgs& args) {
}

void SurfacesScheduler::ScheduledActionSendBeginMainFrame() {
  scheduler_->NotifyBeginMainFrameStarted();
  scheduler_->NotifyReadyToCommit();
}

cc::DrawResult SurfacesScheduler::ScheduledActionDrawAndSwapIfPossible() {
  base::TimeTicks start = base::TimeTicks::Now();
  client_->Draw();
  base::TimeDelta duration = base::TimeTicks::Now() - start;

  draw_estimate_ = (duration + draw_estimate_) / 2;
  return cc::DRAW_SUCCESS;
}

cc::DrawResult SurfacesScheduler::ScheduledActionDrawAndSwapForced() {
  NOTREACHED() << "ScheduledActionDrawAndSwapIfPossible always succeeds.";
  return cc::DRAW_SUCCESS;
}

void SurfacesScheduler::ScheduledActionAnimate() {
}

void SurfacesScheduler::ScheduledActionCommit() {
}

void SurfacesScheduler::ScheduledActionActivateSyncTree() {
}

void SurfacesScheduler::ScheduledActionBeginOutputSurfaceCreation() {
  scheduler_->DidCreateAndInitializeOutputSurface();
}

void SurfacesScheduler::ScheduledActionPrepareTiles() {
}

void SurfacesScheduler::DidAnticipatedDrawTimeChange(base::TimeTicks time) {
}

base::TimeDelta SurfacesScheduler::DrawDurationEstimate() {
  return draw_estimate_;
}

base::TimeDelta SurfacesScheduler::BeginMainFrameToCommitDurationEstimate() {
  return base::TimeDelta();
}

base::TimeDelta SurfacesScheduler::CommitToActivateDurationEstimate() {
  return base::TimeDelta();
}

void SurfacesScheduler::DidBeginImplFrameDeadline() {
}

void SurfacesScheduler::SendBeginFramesToChildren(
    const cc::BeginFrameArgs& args) {
}

}  // namespace mojo
<|endoftext|>


<commit_before>#include "stdafx.h"

#include "BindingHandler.h"
#include "ClientAdapter.h"
#include "CefSharp.h"
#include "IBeforePopup.h"
#include "IBeforeResourceLoad.h"
#include "IBeforeMenu.h"
#include "IAfterResponse.h"
#include "StreamAdapter.h"

namespace CefSharp
{
    bool ClientAdapter::OnBeforePopup(CefRefPtr<CefBrowser> parentBrowser, const CefPopupFeatures& popupFeatures, CefWindowInfo& windowInfo, const CefString& url, CefRefPtr<CefClient>& client, CefBrowserSettings& settings)
    {
        IBeforePopup^ handler = _browserControl->BeforePopupHandler;
        return handler != nullptr &&
            handler->HandleBeforePopup(toClr(url), windowInfo.m_x, windowInfo.m_y, windowInfo.m_nWidth, windowInfo.m_nHeight);
    }

    void ClientAdapter::OnAfterCreated(CefRefPtr<CefBrowser> browser)
    {
        if(!browser->IsPopup())
        {
            _browserHwnd = browser->GetWindowHandle();
            _cefBrowser = browser;

            _browserControl->OnInitialized();
        }
    }

    void ClientAdapter::OnBeforeClose(CefRefPtr<CefBrowser> browser)
    {
        if (_browserHwnd == browser->GetWindowHandle())
        {
            _cefBrowser = nullptr;
        }
    }

    void ClientAdapter::OnAddressChange(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& url)
    {
        if(frame->IsMain())
        {
            _browserControl->SetAddress(toClr(url));
        }
    }

    void ClientAdapter::OnTitleChange(CefRefPtr<CefBrowser> browser, const CefString& title)
    {
        _browserControl->SetTitle(toClr(title));
    }

    bool ClientAdapter::OnTooltip(CefRefPtr<CefBrowser> browser, CefString& text)
    {
        String^ str = toClr(text);

        if (str != _tooltip)
        {
            _tooltip = str;
            _browserControl->SetToolTip(_tooltip);
        }

        return true;
    }

    bool ClientAdapter::OnConsoleMessage(CefRefPtr<CefBrowser> browser, const CefString& message, const CefString& source, int line)
    {
        String^ messageStr = toClr(message);
        String^ sourceStr = toClr(source);
        _browserControl->RaiseConsoleMessage(messageStr, sourceStr, line);

        return true;
    }

    void ClientAdapter::OnLoadStart(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame)
    {
        if (browser->IsPopup())
        {
            return;
        }

        AutoLock lock_scope(this);
        if (frame->IsMain())
        {
            _browserControl->SetNavState(true, false, false);
        }

        _browserControl->AddFrame(frame);
    }

    void ClientAdapter::OnLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int httpStatusCode)
    {
        if(browser->IsPopup())
        {
            return;
        }

        AutoLock lock_scope(this);
        if (frame->IsMain())
        {
            _browserControl->SetNavState(false, browser->CanGoBack(), browser->CanGoForward());
        }

        _browserControl->FrameLoadComplete(frame);
    }

    bool ClientAdapter::OnBeforeResourceLoad(CefRefPtr<CefBrowser> browser, CefRefPtr<CefRequest> request, CefString& redirectUrl, CefRefPtr<CefStreamReader>& resourceStream, CefRefPtr<CefResponse> response, int loadFlags)
    {
        IBeforeResourceLoad^ handler = _browserControl->BeforeResourceLoadHandler;
        if(handler != nullptr)
        {
            CefRequestWrapper^ wrapper = gcnew CefRequestWrapper(request);
            RequestResponse^ requestResponse = gcnew RequestResponse(wrapper);

            handler->HandleBeforeResourceLoad(_browserControl, requestResponse);

            if(requestResponse->Action == ResponseAction::Respond)
            {
                CefRefPtr<StreamAdapter> adapter = new StreamAdapter(requestResponse->ResponseStream);
                resourceStream = CefStreamReader::CreateForHandler(static_cast<CefRefPtr<CefReadHandler>>(adapter));
                //mimeType = toNative(requestResponse->MimeType);
                return false;
            }
            else if(requestResponse->Action == ResponseAction::Cancel)
            {
                return true;
            }
            else if(requestResponse->Action == ResponseAction::Redirect)
            {
                redirectUrl = toNative(requestResponse->RedirectUrl);
            }
        }

        return false;
    }

    void ClientAdapter::OnResourceResponse(CefRefPtr<CefBrowser> browser, const CefString& url, CefRefPtr<CefResponse> response, CefRefPtr<CefContentFilter>& filter)
    {
        IAfterResponse^ handler = _browserControl->AfterResponseHandler;
        if (handler != nullptr)
        {
            String^ cookie = toClr(response->GetHeader("Set-Cookie"));
            if (!String::IsNullOrEmpty(cookie))
            {
                handler->HandleSetCookie(cookie);
            }
        }
    }

    void ClientAdapter::OnJSBinding(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Value> object)
    {
        for each(KeyValuePair<String^, Object^>^ kvp in CEF::GetBoundObjects())
        {
            BindingHandler::Bind(kvp->Key, kvp->Value, object);
        }
    }

    bool ClientAdapter::OnBeforeMenu(CefRefPtr<CefBrowser> browser, const MenuInfo& menuInfo)
    {
        IBeforeMenu^ beforeMenuHandler = _browserControl->BeforeMenuHandler;
        return beforeMenuHandler != nullptr &&
            beforeMenuHandler->HandleBeforeMenu();
    }
}<commit_msg>+response->SetMimeType(toNative(requestResponse->MimeType)); without setting mimeType CEF doesnt start to work with the stream<commit_after>#include "stdafx.h"

#include "BindingHandler.h"
#include "ClientAdapter.h"
#include "CefSharp.h"
#include "IBeforePopup.h"
#include "IBeforeResourceLoad.h"
#include "IBeforeMenu.h"
#include "IAfterResponse.h"
#include "StreamAdapter.h"

namespace CefSharp
{
    bool ClientAdapter::OnBeforePopup(CefRefPtr<CefBrowser> parentBrowser, const CefPopupFeatures& popupFeatures, CefWindowInfo& windowInfo, const CefString& url, CefRefPtr<CefClient>& client, CefBrowserSettings& settings)
    {
        IBeforePopup^ handler = _browserControl->BeforePopupHandler;
        return handler != nullptr &&
            handler->HandleBeforePopup(toClr(url), windowInfo.m_x, windowInfo.m_y, windowInfo.m_nWidth, windowInfo.m_nHeight);
    }

    void ClientAdapter::OnAfterCreated(CefRefPtr<CefBrowser> browser)
    {
        if(!browser->IsPopup())
        {
            _browserHwnd = browser->GetWindowHandle();
            _cefBrowser = browser;

            _browserControl->OnInitialized();
        }
    }

    void ClientAdapter::OnBeforeClose(CefRefPtr<CefBrowser> browser)
    {
        if (_browserHwnd == browser->GetWindowHandle())
        {
            _cefBrowser = nullptr;
        }
    }

    void ClientAdapter::OnAddressChange(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& url)
    {
        if(frame->IsMain())
        {
            _browserControl->SetAddress(toClr(url));
        }
    }

    void ClientAdapter::OnTitleChange(CefRefPtr<CefBrowser> browser, const CefString& title)
    {
        _browserControl->SetTitle(toClr(title));
    }

    bool ClientAdapter::OnTooltip(CefRefPtr<CefBrowser> browser, CefString& text)
    {
        String^ str = toClr(text);

        if (str != _tooltip)
        {
            _tooltip = str;
            _browserControl->SetToolTip(_tooltip);
        }

        return true;
    }

    bool ClientAdapter::OnConsoleMessage(CefRefPtr<CefBrowser> browser, const CefString& message, const CefString& source, int line)
    {
        String^ messageStr = toClr(message);
        String^ sourceStr = toClr(source);
        _browserControl->RaiseConsoleMessage(messageStr, sourceStr, line);

        return true;
    }

    void ClientAdapter::OnLoadStart(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame)
    {
        if (browser->IsPopup())
        {
            return;
        }

        AutoLock lock_scope(this);
        if (frame->IsMain())
        {
            _browserControl->SetNavState(true, false, false);
        }

        _browserControl->AddFrame(frame);
    }

    void ClientAdapter::OnLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int httpStatusCode)
    {
        if(browser->IsPopup())
        {
            return;
        }

        AutoLock lock_scope(this);
        if (frame->IsMain())
        {
            _browserControl->SetNavState(false, browser->CanGoBack(), browser->CanGoForward());
        }

        _browserControl->FrameLoadComplete(frame);
    }

    bool ClientAdapter::OnBeforeResourceLoad(CefRefPtr<CefBrowser> browser, CefRefPtr<CefRequest> request, CefString& redirectUrl, CefRefPtr<CefStreamReader>& resourceStream, CefRefPtr<CefResponse> response, int loadFlags)
    {
        IBeforeResourceLoad^ handler = _browserControl->BeforeResourceLoadHandler;
        if(handler != nullptr)
        {
            CefRequestWrapper^ wrapper = gcnew CefRequestWrapper(request);
            RequestResponse^ requestResponse = gcnew RequestResponse(wrapper);

            handler->HandleBeforeResourceLoad(_browserControl, requestResponse);

            if(requestResponse->Action == ResponseAction::Respond)
            {
                CefRefPtr<StreamAdapter> adapter = new StreamAdapter(requestResponse->ResponseStream);
                resourceStream = CefStreamReader::CreateForHandler(static_cast<CefRefPtr<CefReadHandler>>(adapter));
                response->SetMimeType(toNative(requestResponse->MimeType));
                return false;
            }
            else if(requestResponse->Action == ResponseAction::Cancel)
            {
                return true;
            }
            else if(requestResponse->Action == ResponseAction::Redirect)
            {
                redirectUrl = toNative(requestResponse->RedirectUrl);
            }
        }

        return false;
    }

    void ClientAdapter::OnResourceResponse(CefRefPtr<CefBrowser> browser, const CefString& url, CefRefPtr<CefResponse> response, CefRefPtr<CefContentFilter>& filter)
    {
        IAfterResponse^ handler = _browserControl->AfterResponseHandler;
        if (handler != nullptr)
        {
            String^ cookie = toClr(response->GetHeader("Set-Cookie"));
            if (!String::IsNullOrEmpty(cookie))
            {
                handler->HandleSetCookie(cookie);
            }
        }
    }

    void ClientAdapter::OnJSBinding(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Value> object)
    {
        for each(KeyValuePair<String^, Object^>^ kvp in CEF::GetBoundObjects())
        {
            BindingHandler::Bind(kvp->Key, kvp->Value, object);
        }
    }

    bool ClientAdapter::OnBeforeMenu(CefRefPtr<CefBrowser> browser, const MenuInfo& menuInfo)
    {
        IBeforeMenu^ beforeMenuHandler = _browserControl->BeforeMenuHandler;
        return beforeMenuHandler != nullptr &&
            beforeMenuHandler->HandleBeforeMenu();
    }
}<|endoftext|>


<commit_before>// $Id$
//
// Copyright (C)  2005-2008 Greg Landrum and Rational Discovery LLC
//
//  @@ All Rights Reserved @@
//
#include "RDLog.h"

#if 1
#include <iomanip>
#include <string>
#include <time.h>

boost::logging::rdLogger *rdAppLog=0;
boost::logging::rdLogger *rdDebugLog=0;
boost::logging::rdLogger *rdInfoLog=0;
boost::logging::rdLogger *rdErrorLog=0;
boost::logging::rdLogger *rdWarningLog=0;
boost::logging::rdLogger *rdStatusLog=0;

namespace boost {
  namespace logging {

    void enable_logs(const char *arg) { enable_logs(std::string(arg));};
    void enable_logs(const std::string &arg) {
      // Yes... this is extremely crude
      if(arg=="rdApp.debug"||arg=="rdApp.*"){
        if(rdDebugLog) rdDebugLog->df_enabled=true;
      }
      if(arg=="rdApp.info"||arg=="rdApp.*"){
        if(rdInfoLog) rdInfoLog->df_enabled=true;
      }
      if(arg=="rdApp.warning"||arg=="rdApp.*"){
        if(rdWarningLog) rdWarningLog->df_enabled=true;
      }
      if(arg=="rdApp.error"||arg=="rdApp.*"){
        if(rdErrorLog) rdErrorLog->df_enabled=true;
      }
    };
    void disable_logs(const char *arg) {disable_logs(std::string(arg));};
    void disable_logs(const std::string &arg) {
      // Yes... this is extremely crude
      if(arg=="rdApp.debug"||arg=="rdApp.*"){
        if(rdDebugLog) rdDebugLog->df_enabled=false;
      }
      if(arg=="rdApp.info"||arg=="rdApp.*"){
        if(rdInfoLog) rdInfoLog->df_enabled=false;
      }
      if(arg=="rdApp.warning"||arg=="rdApp.*"){
        if(rdWarningLog) rdWarningLog->df_enabled=false;
      }
      if(arg=="rdApp.error"||arg=="rdApp.*"){
        if(rdErrorLog) rdErrorLog->df_enabled=false;
      }
    };
  }
}

namespace RDLog {
  void InitLogs(){
    rdDebugLog=new boost::logging::rdLogger(&std::cerr);
    rdInfoLog=new boost::logging::rdLogger(&std::cout);
    rdWarningLog=new boost::logging::rdLogger(&std::cerr);
    rdErrorLog=new boost::logging::rdLogger(&std::cerr);
  }
  std::ostream &toStream(std::ostream &logstrm) {
    time_t t = time(0);
    tm details = *localtime( &t);
    logstrm << "["<<std::setw(2)<<std::setfill('0')<<details.tm_hour<<":"<<std::setw(2)<<std::setfill('0')<<details.tm_min<<":"<<std::setw(2)<<std::setfill('0')<<int(details.tm_sec)<<"] ";
    return logstrm;
  }

}

#else
#include <boost/log/functions.hpp>
#if defined(BOOST_HAS_THREADS2)
#include <boost/log/extra/functions_ts.hpp>
#endif
#include <iostream>
namespace logging = boost::logging;

BOOST_DEFINE_LOG(rdAppLog,"rdApp")
BOOST_DEFINE_LOG(rdDebugLog,"rdApp.debug")
BOOST_DEFINE_LOG(rdInfoLog,"rdApp.info")
BOOST_DEFINE_LOG(rdErrorLog,"rdApp.error")
BOOST_DEFINE_LOG(rdWarningLog,"rdApp.warning")
BOOST_DEFINE_LOG(rdStatusLog,"rdApp.status")

namespace RDLog {
  void write_to_cout(const std::string &, const std::string &msg) {
    std::cout << msg; std::cout.flush();
  }
  void write_to_cerr(const std::string &, const std::string &msg) {
    std::cerr << msg; std::cerr.flush();
  }

  void InitLogs(){
    static bool callOnce=true;
    if(!callOnce) return;
    callOnce=false;

    // turn off caching:
    logging::set_log_caching(false);
    logging::manipulate_logs("rdApp.*")
      .add_modifier(logging::prepend_time("[$hh:$mm:$ss] "),
		    logging::DEFAULT_INDEX-10);
    logging::manipulate_logs("rdApp.info")
      .add_appender(write_to_cout,
		    logging::DEFAULT_INDEX+1);
#if defined(BOOST_HAS_THREADS2)
    logging::manipulate_logs("rdApp.error")
      .add_appender(logging::ts_appender(write_to_cerr,100),
		    logging::DEFAULT_INDEX+1);
    logging::manipulate_logs("rdApp.warning")
      .add_appender(logging::ts_appender(write_to_cerr,100),
		    logging::DEFAULT_INDEX+1);
    logging::manipulate_logs("rdApp.status")
      .add_appender(logging::ts_appender(write_to_cerr,100),
		    logging::DEFAULT_INDEX+1);
    logging::manipulate_logs("rdApp.debug")
      .add_appender(logging::ts_appender(write_to_cerr,100),
		    logging::DEFAULT_INDEX+1);
#else
    logging::manipulate_logs("rdApp.error")
      .add_appender(write_to_cerr,
		    logging::DEFAULT_INDEX+1);
    logging::manipulate_logs("rdApp.warning")
      .add_appender(write_to_cerr,
		    logging::DEFAULT_INDEX+1);
    logging::manipulate_logs("rdApp.status")
      .add_appender(write_to_cerr,
		    logging::DEFAULT_INDEX+1);
    logging::manipulate_logs("rdApp.debug")
      .add_appender(write_to_cerr,
		    logging::DEFAULT_INDEX+1);
#endif
    // start with the debug log disabled:
    logging::disable_logs("rdApp.debug");
  };
}
#endif
<commit_msg>add a hack to get the console stuff working on windows. this needs to be tested on lin and mac<commit_after>// $Id$
//
// Copyright (C)  2005-2010 Greg Landrum and Rational Discovery LLC
//
//  @@ All Rights Reserved @@
//
#include "RDLog.h"

#if 1
#include <iomanip>
#include <string>
#include <time.h>

namespace {
  // this is a "bit" of a hack to work around shared/static library problems
  // on windows
  boost::logging::rdLogger cerrLogger(&std::cerr);
  boost::logging::rdLogger coutLogger(&std::cout);
}

boost::logging::rdLogger *rdAppLog=0;
boost::logging::rdLogger *rdDebugLog=0;
boost::logging::rdLogger *rdInfoLog=&coutLogger;
boost::logging::rdLogger *rdErrorLog=&cerrLogger;
boost::logging::rdLogger *rdWarningLog=&cerrLogger;
boost::logging::rdLogger *rdStatusLog=0;

namespace boost {
  namespace logging {

    void enable_logs(const char *arg) { enable_logs(std::string(arg));};
    void enable_logs(const std::string &arg) {
      // Yes... this is extremely crude
      if(arg=="rdApp.debug"||arg=="rdApp.*"){
        if(rdDebugLog) rdDebugLog->df_enabled=true;
      }
      if(arg=="rdApp.info"||arg=="rdApp.*"){
        if(rdInfoLog) rdInfoLog->df_enabled=true;
      }
      if(arg=="rdApp.warning"||arg=="rdApp.*"){
        if(rdWarningLog) rdWarningLog->df_enabled=true;
      }
      if(arg=="rdApp.error"||arg=="rdApp.*"){
        if(rdErrorLog) rdErrorLog->df_enabled=true;
      }
    };
    void disable_logs(const char *arg) {disable_logs(std::string(arg));};
    void disable_logs(const std::string &arg) {
      // Yes... this is extremely crude
      if(arg=="rdApp.debug"||arg=="rdApp.*"){
        if(rdDebugLog) rdDebugLog->df_enabled=false;
      }
      if(arg=="rdApp.info"||arg=="rdApp.*"){
        if(rdInfoLog) rdInfoLog->df_enabled=false;
      }
      if(arg=="rdApp.warning"||arg=="rdApp.*"){
        if(rdWarningLog) rdWarningLog->df_enabled=false;
      }
      if(arg=="rdApp.error"||arg=="rdApp.*"){
        if(rdErrorLog) rdErrorLog->df_enabled=false;
      }
    };
  }
}

namespace RDLog {
  void InitLogs(){
    rdDebugLog=new boost::logging::rdLogger(&std::cerr);
    rdInfoLog=new boost::logging::rdLogger(&std::cout);
    rdWarningLog=new boost::logging::rdLogger(&std::cerr);
    rdErrorLog=new boost::logging::rdLogger(&std::cerr);
  }
  std::ostream &toStream(std::ostream &logstrm) {
    time_t t = time(0);
    tm details = *localtime( &t);
    logstrm << "["<<std::setw(2)<<std::setfill('0')<<details.tm_hour<<":"<<std::setw(2)<<std::setfill('0')<<details.tm_min<<":"<<std::setw(2)<<std::setfill('0')<<int(details.tm_sec)<<"] ";
    return logstrm;
  }

}

#else
#include <boost/log/functions.hpp>
#if defined(BOOST_HAS_THREADS2)
#include <boost/log/extra/functions_ts.hpp>
#endif
#include <iostream>
namespace logging = boost::logging;

BOOST_DEFINE_LOG(rdAppLog,"rdApp")
BOOST_DEFINE_LOG(rdDebugLog,"rdApp.debug")
BOOST_DEFINE_LOG(rdInfoLog,"rdApp.info")
BOOST_DEFINE_LOG(rdErrorLog,"rdApp.error")
BOOST_DEFINE_LOG(rdWarningLog,"rdApp.warning")
BOOST_DEFINE_LOG(rdStatusLog,"rdApp.status")

namespace RDLog {
  void write_to_cout(const std::string &, const std::string &msg) {
    std::cout << msg; std::cout.flush();
  }
  void write_to_cerr(const std::string &, const std::string &msg) {
    std::cerr << msg; std::cerr.flush();
  }

  void InitLogs(){
    static bool callOnce=true;
    if(!callOnce) return;
    callOnce=false;

    // turn off caching:
    logging::set_log_caching(false);
    logging::manipulate_logs("rdApp.*")
      .add_modifier(logging::prepend_time("[$hh:$mm:$ss] "),
		    logging::DEFAULT_INDEX-10);
    logging::manipulate_logs("rdApp.info")
      .add_appender(write_to_cout,
		    logging::DEFAULT_INDEX+1);
#if defined(BOOST_HAS_THREADS2)
    logging::manipulate_logs("rdApp.error")
      .add_appender(logging::ts_appender(write_to_cerr,100),
		    logging::DEFAULT_INDEX+1);
    logging::manipulate_logs("rdApp.warning")
      .add_appender(logging::ts_appender(write_to_cerr,100),
		    logging::DEFAULT_INDEX+1);
    logging::manipulate_logs("rdApp.status")
      .add_appender(logging::ts_appender(write_to_cerr,100),
		    logging::DEFAULT_INDEX+1);
    logging::manipulate_logs("rdApp.debug")
      .add_appender(logging::ts_appender(write_to_cerr,100),
		    logging::DEFAULT_INDEX+1);
#else
    logging::manipulate_logs("rdApp.error")
      .add_appender(write_to_cerr,
		    logging::DEFAULT_INDEX+1);
    logging::manipulate_logs("rdApp.warning")
      .add_appender(write_to_cerr,
		    logging::DEFAULT_INDEX+1);
    logging::manipulate_logs("rdApp.status")
      .add_appender(write_to_cerr,
		    logging::DEFAULT_INDEX+1);
    logging::manipulate_logs("rdApp.debug")
      .add_appender(write_to_cerr,
		    logging::DEFAULT_INDEX+1);
#endif
    // start with the debug log disabled:
    logging::disable_logs("rdApp.debug");
  };
}
#endif
<|endoftext|>