<commit_before>// ROOT
#include "TFile.h"
#include "TList.h"
#include "TH1.h"
#include "TH2.h"
#include "TH3.h"
#include "TF1.h"
#include "TFormula.h"
#include "TRandom.h"
#include "TSpline.h"

// analysis framework
#include "AliAnalysisManager.h"
#include "AliInputEventHandler.h"
#include "AliVEvent.h"
#include "AliVTrack.h"
#include "AliVVertex.h"
#include "AliVMultiplicity.h"

// MC stuff
#include "AliMCEvent.h"
#include "AliGenPythiaEventHeader.h"

// ESD stuff
#include "AliESDEvent.h"
#include "AliESDInputHandler.h"
#include "AliESDtrack.h"
#include "AliESDtrackCuts.h"

// AOD stuff
#include "AliAODEvent.h"
#include "AliAODJet.h"
#include "AliAODTrack.h"

// EMCAL framework and jet tasks
#include "AliJetContainer.h"
#include "AliParticleContainer.h"
#include "AliClusterContainer.h"
#include "AliEmcalJet.h"

#include "AliAnalysisTaskEmcalJet.h"
#include "AliAnalysisTaskJetsEvshape.h"

#include <iostream>
#include <cmath>

AliAnalysisTaskJetsEvshape::AliAnalysisTaskJetsEvshape(const char *name) :
  AliAnalysisTaskEmcalJet(name, kTRUE),
  fMCEvent(0x0),
  fESDEvent(0x0),
  fAODEvent(0x0),
  fRunNumber(-1),
  fJetsCont(0),
  fTracksCont(0),
  fCaloClustersCont(0),
  fOutputList(0x0),
  fShortTaskId("jets_evshape")
{
  // default ctor

  SetMakeGeneralHistograms(kTRUE);

  DefineOutput(kOutputEmcal, TList::Class());
  AliInfo(Form("creating output slot #%i", kOutputTask));
  DefineOutput(kOutputTask, TList::Class());
}

AliAnalysisTaskJetsEvshape::~AliAnalysisTaskJetsEvshape()
{
  // dtor
}

void AliAnalysisTaskJetsEvshape::UserCreateOutputObjects()
{
  // create user output objects
  AliInfo("creating output objects");

  // common EMCAL framework
  AliAnalysisTaskEmcalJet::UserCreateOutputObjects();
  PostData(kOutputEmcal, fOutput);
  fJetsCont           = GetJetContainer(0);
  printf("setup jet container: %p, from available:\n", fJetsCont);
  fJetCollArray.Print();
  printf("end\n");
  if(fJetsCont) { //get particles and clusters connected to jets
    fTracksCont       = fJetsCont->GetParticleContainer();
    fCaloClustersCont = fJetsCont->GetClusterContainer();
  } else {        //no jets, just analysis tracks and clusters
    fTracksCont       = GetParticleContainer(0);
    fCaloClustersCont = GetClusterContainer(0);
  }
  if(fTracksCont) fTracksCont->SetClassName("AliVTrack");
  if(fCaloClustersCont) fCaloClustersCont->SetClassName("AliVCluster");

  // setup list
  OpenFile(kOutputTask);
  fOutputList = new TList();
  fOutputList->SetOwner();

  // setup histograms
  TH1 *hist;
  TH1 *histStat = AddHistogram(ID(kHistStat), "event statistics;;counts",
                               kStatLast-1, .5, kStatLast-.5);
  histStat->GetXaxis()->SetBinLabel(ID(kStatSeen));
  histStat->GetXaxis()->SetBinLabel(ID(kStatTrg));
  histStat->GetXaxis()->SetBinLabel(ID(kStatUsed));
  histStat->GetXaxis()->SetBinLabel(ID(kStatEvCuts));

  AddHistogram(ID(kHistJetPt), "jet spectrum;p_{T}^{jet,ch} (GeV/#it{c});counts",
               40, 0., 40.);
  AddHistogram(ID(kHistMult), "tracklet multiplicity;N_{trkl};counts",
               100, 0., 400.);

  PostData(kOutputTask, fOutputList);
}

Bool_t AliAnalysisTaskJetsEvshape::Notify()
{
  // actions to be taken upon notification about input file change

  return AliAnalysisTaskEmcalJet::Notify();
}

void AliAnalysisTaskJetsEvshape::Terminate(const Option_t *option)
{
  // actions at task termination

  AliAnalysisTaskEmcalJet::Terminate(option);
}

void AliAnalysisTaskJetsEvshape::PrintTask(Option_t *option, Int_t indent) const
{
  AliAnalysisTaskEmcalJet::PrintTask(option, indent);

  std::cout << std::setw(indent) << " " << "nothing to say: " << std::endl;
}

Bool_t AliAnalysisTaskJetsEvshape::PrepareEvent()
{
  Bool_t eventGood = kTRUE;

  // check for run change
  if (fRunNumber != InputEvent()->GetRunNumber()) {
    fRunNumber = InputEvent()->GetRunNumber();
  }

  return eventGood;
}

Bool_t AliAnalysisTaskJetsEvshape::CleanUpEvent()
{
  return kTRUE;
}

void AliAnalysisTaskJetsEvshape::ExecOnce()
{
  AliAnalysisTaskEmcalJet::ExecOnce();
}

Bool_t AliAnalysisTaskJetsEvshape::Run()
{
  return kTRUE;
}

Bool_t AliAnalysisTaskJetsEvshape::FillHistograms()
{
  FillH1(kHistStat, kStatUsed);

  AliVMultiplicity *mult = InputEvent()->GetMultiplicity();
  Int_t nTracklets = mult->GetNumberOfTracklets();
  FillH1(kHistMult, nTracklets);

  if (fJetsCont) {
    fJetsCont->ResetCurrentID();
    AliEmcalJet *jet = fJetsCont->GetNextAcceptJet();
    Int_t i = 0;
    while (jet) {
      FillH1(kHistJetPt, jet->Pt());
      jet = fJetsCont->GetNextAcceptJet();
    }
  }

  return kTRUE;
}

void AliAnalysisTaskJetsEvshape::UserExec(Option_t *option)
{
  // actual work

  AliAnalysisTaskEmcalJet::UserExec(option);

  // setup pointers to input data (null if unavailable)
  // mcEvent:  MC input
  // esdEvent: ESD input
  // outEvent: AOD output
  // aodEvent: AOD input if available, otherwise AOD output

  fMCEvent   = this->MCEvent();
  fESDEvent  = dynamic_cast<AliESDEvent*>(this->InputEvent()); // could also be AOD input
  AliAODEvent* outEvent  = this->AODEvent();
  fAODEvent  = dynamic_cast<AliAODEvent*> (this->InputEvent());
  if (!fAODEvent)
    fAODEvent = outEvent;

  if ((fDebug > 0) && fESDEvent)
    printf("event: %s-%06i\n", CurrentFileName(), fESDEvent->GetEventNumberInFile());

  // record number of sampled events and detect trigger contributions
  FillH1(kHistStat, kStatSeen);

  // so far, no trigger selection, we accept all
  FillH1(kHistStat, kStatTrg);

  // prepare the event
  // (make sure it is cleaned up in the end)
  if (PrepareEvent()) {
    // here we have passed the event cuts
    FillH1(kHistStat, kStatEvCuts);

    // multiplicity selection

    // event shape selection

    InputEvent()->GetList()->ls();
  }

 stop:
  CleanUpEvent();

  PostData(kOutputEmcal, fOutput);
  PostData(kOutputTask, fOutputList);
}

// ----- histogram management -----
TH1* AliAnalysisTaskJetsEvshape::AddHistogram(Hist_t hist, const char *hid, TString title,
						 Int_t xbins, Float_t xmin, Float_t xmax,
						 Int_t binType)
{
  TString hName;
  hName.Form("%s_%s", fShortTaskId, hid);
  hName.ToLower();
  TH1 *h = 0x0;
  if (binType == 0)
    h = new TH1I(hName.Data(), title,
                 xbins, xmin, xmax);
  else
    h = new TH1F(hName.Data(), title,
                 xbins, xmin, xmax);
  GetHistogram(hist) = h;
  fOutputList->Add(h);
  return h;
}

TH2* AliAnalysisTaskJetsEvshape::AddHistogram(Hist_t hist, const char *hid, TString title,
						 Int_t xbins, Float_t xmin, Float_t xmax,
						 Int_t ybins, Float_t ymin, Float_t ymax,
						 Int_t binType)
{
  TString hName;
  hName.Form("%s_%s", fShortTaskId, hid);
  hName.ToLower();
  TH1 *h = 0x0;
  if (binType == 0)
    h = GetHistogram(hist) = new TH2I(hName.Data(), title,
                                     xbins, xmin, xmax,
                                     ybins, ymin, ymax);
  else
    h = GetHistogram(hist) = new TH2F(hName.Data(), title,
                                     xbins, xmin, xmax,
                                     ybins, ymin, ymax);
  fOutputList->Add(h);
  return (TH2*) h;
}

TH3* AliAnalysisTaskJetsEvshape::AddHistogram(Hist_t hist, const char *hid, TString title,
						 Int_t xbins, Float_t xmin, Float_t xmax,
						 Int_t ybins, Float_t ymin, Float_t ymax,
						 Int_t zbins, Float_t zmin, Float_t zmax,
						 Int_t binType)
{
  TString hName;
  hName.Form("%s_%s", fShortTaskId, hid);
  hName.ToLower();
  TH1 *h = 0x0;
  if (binType == 0)
    h = GetHistogram(hist) = new TH3I(hName.Data(), title,
                                     xbins, xmin, xmax,
                                     ybins, ymin, ymax,
                                     zbins, zmin, zmax);
  else
    h = GetHistogram(hist) = new TH3F(hName.Data(), title,
                                     xbins, xmin, xmax,
                                     ybins, ymin, ymax,
                                     zbins, zmin, zmax);
  fOutputList->Add(h);
  return (TH3*) h;
}
<commit_msg>disable debug output<commit_after>// ROOT
#include "TFile.h"
#include "TList.h"
#include "TH1.h"
#include "TH2.h"
#include "TH3.h"
#include "TF1.h"
#include "TFormula.h"
#include "TRandom.h"
#include "TSpline.h"

// analysis framework
#include "AliAnalysisManager.h"
#include "AliInputEventHandler.h"
#include "AliVEvent.h"
#include "AliVTrack.h"
#include "AliVVertex.h"
#include "AliVMultiplicity.h"

// MC stuff
#include "AliMCEvent.h"
#include "AliGenPythiaEventHeader.h"

// ESD stuff
#include "AliESDEvent.h"
#include "AliESDInputHandler.h"
#include "AliESDtrack.h"
#include "AliESDtrackCuts.h"

// AOD stuff
#include "AliAODEvent.h"
#include "AliAODJet.h"
#include "AliAODTrack.h"

// EMCAL framework and jet tasks
#include "AliJetContainer.h"
#include "AliParticleContainer.h"
#include "AliClusterContainer.h"
#include "AliEmcalJet.h"

#include "AliAnalysisTaskEmcalJet.h"
#include "AliAnalysisTaskJetsEvshape.h"

#include <iostream>
#include <cmath>

AliAnalysisTaskJetsEvshape::AliAnalysisTaskJetsEvshape(const char *name) :
  AliAnalysisTaskEmcalJet(name, kTRUE),
  fMCEvent(0x0),
  fESDEvent(0x0),
  fAODEvent(0x0),
  fRunNumber(-1),
  fJetsCont(0),
  fTracksCont(0),
  fCaloClustersCont(0),
  fOutputList(0x0),
  fShortTaskId("jets_evshape")
{
  // default ctor

  SetMakeGeneralHistograms(kTRUE);

  DefineOutput(kOutputEmcal, TList::Class());
  AliInfo(Form("creating output slot #%i", kOutputTask));
  DefineOutput(kOutputTask, TList::Class());
}

AliAnalysisTaskJetsEvshape::~AliAnalysisTaskJetsEvshape()
{
  // dtor
}

void AliAnalysisTaskJetsEvshape::UserCreateOutputObjects()
{
  // create user output objects
  AliInfo("creating output objects");

  // common EMCAL framework
  AliAnalysisTaskEmcalJet::UserCreateOutputObjects();
  PostData(kOutputEmcal, fOutput);
  fJetsCont           = GetJetContainer(0);
  printf("setup jet container: %p, from available:\n", fJetsCont);
  fJetCollArray.Print();
  printf("end\n");
  if(fJetsCont) { //get particles and clusters connected to jets
    fTracksCont       = fJetsCont->GetParticleContainer();
    fCaloClustersCont = fJetsCont->GetClusterContainer();
  } else {        //no jets, just analysis tracks and clusters
    fTracksCont       = GetParticleContainer(0);
    fCaloClustersCont = GetClusterContainer(0);
  }
  if(fTracksCont) fTracksCont->SetClassName("AliVTrack");
  if(fCaloClustersCont) fCaloClustersCont->SetClassName("AliVCluster");

  // setup list
  OpenFile(kOutputTask);
  fOutputList = new TList();
  fOutputList->SetOwner();

  // setup histograms
  TH1 *hist;
  TH1 *histStat = AddHistogram(ID(kHistStat), "event statistics;;counts",
                               kStatLast-1, .5, kStatLast-.5);
  histStat->GetXaxis()->SetBinLabel(ID(kStatSeen));
  histStat->GetXaxis()->SetBinLabel(ID(kStatTrg));
  histStat->GetXaxis()->SetBinLabel(ID(kStatUsed));
  histStat->GetXaxis()->SetBinLabel(ID(kStatEvCuts));

  AddHistogram(ID(kHistJetPt), "jet spectrum;p_{T}^{jet,ch} (GeV/#it{c});counts",
               40, 0., 40.);
  AddHistogram(ID(kHistMult), "tracklet multiplicity;N_{trkl};counts",
               100, 0., 400.);

  PostData(kOutputTask, fOutputList);
}

Bool_t AliAnalysisTaskJetsEvshape::Notify()
{
  // actions to be taken upon notification about input file change

  return AliAnalysisTaskEmcalJet::Notify();
}

void AliAnalysisTaskJetsEvshape::Terminate(const Option_t *option)
{
  // actions at task termination

  AliAnalysisTaskEmcalJet::Terminate(option);
}

void AliAnalysisTaskJetsEvshape::PrintTask(Option_t *option, Int_t indent) const
{
  AliAnalysisTaskEmcalJet::PrintTask(option, indent);

  std::cout << std::setw(indent) << " " << "nothing to say: " << std::endl;
}

Bool_t AliAnalysisTaskJetsEvshape::PrepareEvent()
{
  Bool_t eventGood = kTRUE;

  // check for run change
  if (fRunNumber != InputEvent()->GetRunNumber()) {
    fRunNumber = InputEvent()->GetRunNumber();
  }

  return eventGood;
}

Bool_t AliAnalysisTaskJetsEvshape::CleanUpEvent()
{
  return kTRUE;
}

void AliAnalysisTaskJetsEvshape::ExecOnce()
{
  AliAnalysisTaskEmcalJet::ExecOnce();
}

Bool_t AliAnalysisTaskJetsEvshape::Run()
{
  return kTRUE;
}

Bool_t AliAnalysisTaskJetsEvshape::FillHistograms()
{
  FillH1(kHistStat, kStatUsed);

  AliVMultiplicity *mult = InputEvent()->GetMultiplicity();
  Int_t nTracklets = mult->GetNumberOfTracklets();
  FillH1(kHistMult, nTracklets);

  if (fJetsCont) {
    fJetsCont->ResetCurrentID();
    AliEmcalJet *jet = fJetsCont->GetNextAcceptJet();
    Int_t i = 0;
    while (jet) {
      FillH1(kHistJetPt, jet->Pt());
      jet = fJetsCont->GetNextAcceptJet();
    }
  }

  return kTRUE;
}

void AliAnalysisTaskJetsEvshape::UserExec(Option_t *option)
{
  // actual work

  AliAnalysisTaskEmcalJet::UserExec(option);

  // setup pointers to input data (null if unavailable)
  // mcEvent:  MC input
  // esdEvent: ESD input
  // outEvent: AOD output
  // aodEvent: AOD input if available, otherwise AOD output

  fMCEvent   = this->MCEvent();
  fESDEvent  = dynamic_cast<AliESDEvent*>(this->InputEvent()); // could also be AOD input
  AliAODEvent* outEvent  = this->AODEvent();
  fAODEvent  = dynamic_cast<AliAODEvent*> (this->InputEvent());
  if (!fAODEvent)
    fAODEvent = outEvent;

  if ((fDebug > 0) && fESDEvent)
    printf("event: %s-%06i\n", CurrentFileName(), fESDEvent->GetEventNumberInFile());

  // record number of sampled events and detect trigger contributions
  FillH1(kHistStat, kStatSeen);

  // so far, no trigger selection, we accept all
  FillH1(kHistStat, kStatTrg);

  // prepare the event
  // (make sure it is cleaned up in the end)
  if (PrepareEvent()) {
    // here we have passed the event cuts
    FillH1(kHistStat, kStatEvCuts);

    // multiplicity selection

    // event shape selection

    // InputEvent()->GetList()->ls();
  }

 stop:
  CleanUpEvent();

  PostData(kOutputEmcal, fOutput);
  PostData(kOutputTask, fOutputList);
}

// ----- histogram management -----
TH1* AliAnalysisTaskJetsEvshape::AddHistogram(Hist_t hist, const char *hid, TString title,
						 Int_t xbins, Float_t xmin, Float_t xmax,
						 Int_t binType)
{
  TString hName;
  hName.Form("%s_%s", fShortTaskId, hid);
  hName.ToLower();
  TH1 *h = 0x0;
  if (binType == 0)
    h = new TH1I(hName.Data(), title,
                 xbins, xmin, xmax);
  else
    h = new TH1F(hName.Data(), title,
                 xbins, xmin, xmax);
  GetHistogram(hist) = h;
  fOutputList->Add(h);
  return h;
}

TH2* AliAnalysisTaskJetsEvshape::AddHistogram(Hist_t hist, const char *hid, TString title,
						 Int_t xbins, Float_t xmin, Float_t xmax,
						 Int_t ybins, Float_t ymin, Float_t ymax,
						 Int_t binType)
{
  TString hName;
  hName.Form("%s_%s", fShortTaskId, hid);
  hName.ToLower();
  TH1 *h = 0x0;
  if (binType == 0)
    h = GetHistogram(hist) = new TH2I(hName.Data(), title,
                                     xbins, xmin, xmax,
                                     ybins, ymin, ymax);
  else
    h = GetHistogram(hist) = new TH2F(hName.Data(), title,
                                     xbins, xmin, xmax,
                                     ybins, ymin, ymax);
  fOutputList->Add(h);
  return (TH2*) h;
}

TH3* AliAnalysisTaskJetsEvshape::AddHistogram(Hist_t hist, const char *hid, TString title,
						 Int_t xbins, Float_t xmin, Float_t xmax,
						 Int_t ybins, Float_t ymin, Float_t ymax,
						 Int_t zbins, Float_t zmin, Float_t zmax,
						 Int_t binType)
{
  TString hName;
  hName.Form("%s_%s", fShortTaskId, hid);
  hName.ToLower();
  TH1 *h = 0x0;
  if (binType == 0)
    h = GetHistogram(hist) = new TH3I(hName.Data(), title,
                                     xbins, xmin, xmax,
                                     ybins, ymin, ymax,
                                     zbins, zmin, zmax);
  else
    h = GetHistogram(hist) = new TH3F(hName.Data(), title,
                                     xbins, xmin, xmax,
                                     ybins, ymin, ymax,
                                     zbins, zmin, zmax);
  fOutputList->Add(h);
  return (TH3*) h;
}
<|endoftext|>


<commit_before>#include <Ogre.h>
#include <utility>
#include "core/engine.h"
#include "core/entity.h"
#include "core/system_loader.h"

#include "ogrerender.h"

using namespace Ogre;

Ygg::OgreRenderSystem::OgreRenderSystem(unsigned long window, SystemLoader *loader)
    :m_parentwindow(window),
      m_loader(loader)
{
}

Ygg::OgreRenderSystem::~OgreRenderSystem()
{
	delete m_root;
}

void Ygg::OgreRenderSystem::Init(Ygg::Engine *engine)
{
	m_root = new Ogre::Root("", "", "");

	// Load required systems
	Ogre::StringVector required_plugins;
	required_plugins.push_back("./RenderSystem_GL");
	required_plugins.push_back("./Plugin_OctreeSceneManager");

	for (auto it = required_plugins.begin(); it != required_plugins.end(); ++it) {
#ifdef _DEBUG
		m_root->loadPlugin(*it + Ogre::String("_d"));
#else
		m_root->loadPlugin(*it);
#endif
	}

	// ToDo, check that plugins were actually loaded

	m_root->setRenderSystem(m_root->getRenderSystemByName("OpenGL Rendering Subsystem"));
	m_root->initialise(false);

	// Setup the window
	Ogre::NameValuePairList params;
	params.insert(std::make_pair("parentWindowHandle", Ogre::StringConverter::toString(m_parentwindow)));

	m_window = m_root->createRenderWindow("Yggdrasil", 800, 600, false, &params);
	m_window->setVisible(true);

	// Setup the scenemanager
	m_scenemgr = m_root->createSceneManager("OctreeSceneManager", "DefaultSceneManager");

	// Setup the camera
	m_camera = m_scenemgr->createCamera("Camera");
	m_camera->setPosition(Ogre::Vector3(10, 10, 10));
	m_camera->lookAt(Ogre::Vector3(0, 0, 0));
	m_camera->setNearClipDistance(5);

	// Setup the viewport
	Ogre::Viewport *vp = m_window->addViewport(m_camera);
	vp->setBackgroundColour(Ogre::ColourValue(0.5f, 1.0f, 0.0f));

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

	// Create a default material
	Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create(
	                                 "DefaultMaterial",
	                                 Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	material->getTechnique(0)->getPass(0)->setVertexColourTracking(Ogre::TVC_AMBIENT);
	material->getTechnique(0)->getPass(0)->setDiffuse(Ogre::ColourValue(0.0, 0.2, 1.0, 0.0));

	// Set ambient light
	m_scenemgr->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5));

	// Create a light
	Ogre::Light *light = m_scenemgr->createLight("MainLight");
	light->setPosition(20, 80, 50);
}

static void convert_mesh(const std::string& mname, Ygg::Mesh *mdata)
{
	Ogre::MeshPtr mesh = Ogre::MeshManager::getSingleton().createManual(mname, "General");
	Ogre::SubMesh *submesh = mesh->createSubMesh();

	const size_t nverts = mdata->vertices.size();
	float verts[3 * 2 * nverts];
	const size_t ibufcount = 3 * mdata->indices.size();
	unsigned short faces[ibufcount];

	for (size_t i = 0; i < nverts; ++i) {
		verts[6*i+0] = mdata->vertices[i].x;
		verts[6*i+1] = mdata->vertices[i].y;
		verts[6*i+2] = mdata->vertices[i].z;

		verts[6*i+3] = mdata->normals[i].x;
		verts[6*i+4] = mdata->normals[i].y;
		verts[6*i+5] = mdata->normals[i].z;
	}

	for (size_t i = 0; i < mdata->indices.size(); ++i) {
		faces[i] = mdata->indices[i];
	}

	mesh->sharedVertexData = new Ogre::VertexData();
	mesh->sharedVertexData->vertexCount = nverts;
	mesh->sharedVertexData->vertexStart = 0;

	// Create declaration (memory format) of vertex data
	Ogre::VertexDeclaration *decl = mesh->sharedVertexData->vertexDeclaration;
	size_t offset = 0;

	offset += decl->addElement(0, offset, Ogre::VET_FLOAT3, Ogre::VES_POSITION).getSize();

	offset += decl->addElement(0, offset, Ogre::VET_FLOAT3, Ogre::VES_NORMAL).getSize();

	// Allocate vertex buffer
	Ogre::HardwareVertexBufferSharedPtr vbuf = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(
	                                               decl->getVertexSize(0), nverts,
	                                               Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY);

	// Upload the vertex data to the GPU
	vbuf->writeData(0, vbuf->getSizeInBytes(), verts, true);

	// Bind the vertex buffer
	Ogre::VertexBufferBinding *binding = mesh->sharedVertexData->vertexBufferBinding;
	binding->setBinding(0, vbuf);

	// Allocate index buffer
	Ogre::HardwareIndexBufferSharedPtr ibuf = Ogre::HardwareBufferManager::getSingleton().createIndexBuffer(
	                                              Ogre::HardwareIndexBuffer::IT_16BIT,
	                                              ibufcount,
	                                              Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY);

	// Upload the index data to the GPU
	ibuf->writeData(0, ibuf->getSizeInBytes(), faces, true);

	// Set parameters of the submesh
	submesh->useSharedVertices = true;
	submesh->indexData->indexBuffer = ibuf;
	submesh->indexData->indexCount = ibufcount;
	submesh->indexData->indexStart = 0;

	// Set bounding information for culling
	// ToDo set better bounds
	mesh->_setBounds(Ogre::AxisAlignedBox(-100, -100, -100, 100, 100, 100));
	mesh->_setBoundingSphereRadius(1000);

	mesh->load();
}

void Ygg::OgreRenderSystem::Convert(Ygg::Engine *engine, std::vector<Entity> *entity_queue)
{
	for (auto it = entity_queue->begin(); it != entity_queue->end(); ++it) {
		Entity *entity = &(*it);

		std::cout << "OGRE: Converting " << entity->name << std::endl;

		// Convert mesh
		MeshComponent *mesh_component = (MeshComponent*)engine->GetComponent(entity, SystemLoader::CID_MESH);
		if (mesh_component != NULL)
		{
			std::cout << "\tFound Mesh" << std::endl;
			convert_mesh(entity->name, &(*m_loader->GetMeshes())[mesh_component->mesh_handles[0]]);
			Ogre::Entity *head = m_scenemgr->createEntity(entity->name, entity->name);
			head->setMaterialName("DefaultMaterial");

			Ogre::SceneNode *headnode = m_scenemgr->getRootSceneNode()->createChildSceneNode();
			headnode->attachObject(head);
			headnode->setPosition(0, 0, 0);
		}
	}
}

void Ygg::OgreRenderSystem::Update(Ygg::Engine *engine, float dt)
{
	m_root->renderOneFrame();
}
<commit_msg>OgreRender: Using externalWindowHandle instead of parentWindowHandle.<commit_after>#include <Ogre.h>
#include <utility>
#include "core/engine.h"
#include "core/entity.h"
#include "core/system_loader.h"

#include "ogrerender.h"

using namespace Ogre;

Ygg::OgreRenderSystem::OgreRenderSystem(unsigned long window, SystemLoader *loader)
    :m_parentwindow(window),
      m_loader(loader)
{
}

Ygg::OgreRenderSystem::~OgreRenderSystem()
{
	delete m_root;
}

void Ygg::OgreRenderSystem::Init(Ygg::Engine *engine)
{
	m_root = new Ogre::Root("", "", "");

	// Load required systems
	Ogre::StringVector required_plugins;
	required_plugins.push_back("./RenderSystem_GL");
	required_plugins.push_back("./Plugin_OctreeSceneManager");

	for (auto it = required_plugins.begin(); it != required_plugins.end(); ++it) {
#ifdef _DEBUG
		m_root->loadPlugin(*it + Ogre::String("_d"));
#else
		m_root->loadPlugin(*it);
#endif
	}

	// ToDo, check that plugins were actually loaded

	m_root->setRenderSystem(m_root->getRenderSystemByName("OpenGL Rendering Subsystem"));
	m_root->initialise(false);

	// Setup the window
	Ogre::NameValuePairList params;
	params.insert(std::make_pair("externalWindowHandle", Ogre::StringConverter::toString(m_parentwindow)));

	m_window = m_root->createRenderWindow("Yggdrasil", 800, 600, false, &params);
	m_window->setVisible(true);

	// Setup the scenemanager
	m_scenemgr = m_root->createSceneManager("OctreeSceneManager", "DefaultSceneManager");

	// Setup the camera
	m_camera = m_scenemgr->createCamera("Camera");
	m_camera->setPosition(Ogre::Vector3(10, 10, 10));
	m_camera->lookAt(Ogre::Vector3(0, 0, 0));
	m_camera->setNearClipDistance(5);

	// Setup the viewport
	Ogre::Viewport *vp = m_window->addViewport(m_camera);
	vp->setBackgroundColour(Ogre::ColourValue(0.5f, 1.0f, 0.0f));

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

	// Create a default material
	Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create(
	                                 "DefaultMaterial",
	                                 Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	material->getTechnique(0)->getPass(0)->setVertexColourTracking(Ogre::TVC_AMBIENT);
	material->getTechnique(0)->getPass(0)->setDiffuse(Ogre::ColourValue(0.0, 0.2, 1.0, 0.0));

	// Set ambient light
	m_scenemgr->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5));

	// Create a light
	Ogre::Light *light = m_scenemgr->createLight("MainLight");
	light->setPosition(20, 80, 50);
}

static void convert_mesh(const std::string& mname, Ygg::Mesh *mdata)
{
	Ogre::MeshPtr mesh = Ogre::MeshManager::getSingleton().createManual(mname, "General");
	Ogre::SubMesh *submesh = mesh->createSubMesh();

	const size_t nverts = mdata->vertices.size();
	float verts[3 * 2 * nverts];
	const size_t ibufcount = 3 * mdata->indices.size();
	unsigned short faces[ibufcount];

	for (size_t i = 0; i < nverts; ++i) {
		verts[6*i+0] = mdata->vertices[i].x;
		verts[6*i+1] = mdata->vertices[i].y;
		verts[6*i+2] = mdata->vertices[i].z;

		verts[6*i+3] = mdata->normals[i].x;
		verts[6*i+4] = mdata->normals[i].y;
		verts[6*i+5] = mdata->normals[i].z;
	}

	for (size_t i = 0; i < mdata->indices.size(); ++i) {
		faces[i] = mdata->indices[i];
	}

	mesh->sharedVertexData = new Ogre::VertexData();
	mesh->sharedVertexData->vertexCount = nverts;
	mesh->sharedVertexData->vertexStart = 0;

	// Create declaration (memory format) of vertex data
	Ogre::VertexDeclaration *decl = mesh->sharedVertexData->vertexDeclaration;
	size_t offset = 0;

	offset += decl->addElement(0, offset, Ogre::VET_FLOAT3, Ogre::VES_POSITION).getSize();

	offset += decl->addElement(0, offset, Ogre::VET_FLOAT3, Ogre::VES_NORMAL).getSize();

	// Allocate vertex buffer
	Ogre::HardwareVertexBufferSharedPtr vbuf = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(
	                                               decl->getVertexSize(0), nverts,
	                                               Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY);

	// Upload the vertex data to the GPU
	vbuf->writeData(0, vbuf->getSizeInBytes(), verts, true);

	// Bind the vertex buffer
	Ogre::VertexBufferBinding *binding = mesh->sharedVertexData->vertexBufferBinding;
	binding->setBinding(0, vbuf);

	// Allocate index buffer
	Ogre::HardwareIndexBufferSharedPtr ibuf = Ogre::HardwareBufferManager::getSingleton().createIndexBuffer(
	                                              Ogre::HardwareIndexBuffer::IT_16BIT,
	                                              ibufcount,
	                                              Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY);

	// Upload the index data to the GPU
	ibuf->writeData(0, ibuf->getSizeInBytes(), faces, true);

	// Set parameters of the submesh
	submesh->useSharedVertices = true;
	submesh->indexData->indexBuffer = ibuf;
	submesh->indexData->indexCount = ibufcount;
	submesh->indexData->indexStart = 0;

	// Set bounding information for culling
	// ToDo set better bounds
	mesh->_setBounds(Ogre::AxisAlignedBox(-100, -100, -100, 100, 100, 100));
	mesh->_setBoundingSphereRadius(1000);

	mesh->load();
}

void Ygg::OgreRenderSystem::Convert(Ygg::Engine *engine, std::vector<Entity> *entity_queue)
{
	for (auto it = entity_queue->begin(); it != entity_queue->end(); ++it) {
		Entity *entity = &(*it);

		std::cout << "OGRE: Converting " << entity->name << std::endl;

		// Convert mesh
		MeshComponent *mesh_component = (MeshComponent*)engine->GetComponent(entity, SystemLoader::CID_MESH);
		if (mesh_component != NULL)
		{
			std::cout << "\tFound Mesh" << std::endl;
			convert_mesh(entity->name, &(*m_loader->GetMeshes())[mesh_component->mesh_handles[0]]);
			Ogre::Entity *head = m_scenemgr->createEntity(entity->name, entity->name);
			head->setMaterialName("DefaultMaterial");

			Ogre::SceneNode *headnode = m_scenemgr->getRootSceneNode()->createChildSceneNode();
			headnode->attachObject(head);
			headnode->setPosition(0, 0, 0);
		}
	}
}

void Ygg::OgreRenderSystem::Update(Ygg::Engine *engine, float dt)
{
	m_root->renderOneFrame();
}
<|endoftext|>


<commit_before>/*
** Copyright 2011-2012 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <QFile>
#include <rrd.h>
#include <sstream>
#include <string.h>
#include <unistd.h>
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/rrd/exceptions/open.hh"
#include "com/centreon/broker/rrd/exceptions/update.hh"
#include "com/centreon/broker/rrd/lib.hh"

using namespace com::centreon::broker;
using namespace com::centreon::broker::rrd;

/**************************************
*                                     *
*           Public Methods            *
*                                     *
**************************************/

/**
 *  Default constructor.
 */
lib::lib() {}

/**
 *  Copy constructor.
 *
 *  @param[in] l Object to copy.
 */
lib::lib(lib const& l)
  : backend(l), _filename(l._filename), _metric(l._metric) {}

/**
 *  Destructor.
 */
lib::~lib() {}

/**
 *  Assignment operator.
 *
 *  @param[in] l Object to copy.
 *
 *  @return This object.
 */
lib& lib::operator=(lib const& l) {
  backend::operator=(l);
  _filename = l._filename;
  _metric = l._metric;
  return (*this);
}

/**
 *  @brief Initiates the bulk load of multiple commands.
 *
 *  With the librrd backend, this method does nothing.
 */
void lib::begin() {
  return ;
}

/**
 *  Close the RRD file.
 */
void lib::close() {
  _filename.clear();
  _metric.clear();
  return ;
}

/**
 *  @brief Commit transaction started with begin().
 *
 *  With the librrd backend, the method does nothing.
 */
void lib::commit() {
  return ;
}

/**
 *  Normalize a metric name.
 *
 *  @param[in] metric Metric name.
 *
 *  @return Normalized metric name.
 */
QString lib::normalize_metric_name(QString const& metric) {
  QString normalized(metric.toLatin1());
  normalized.replace("/", "slash_");
  normalized.replace("#S#", "slash_");
  normalized.replace("\\", "bslash_");
  normalized.replace("#BS#", "bslash_");
  normalized.replace("%", "pct_");
  normalized.replace("#P#", "pct_");
  for (unsigned int i(0), size(normalized.size()); i < size; ++i) {
    char current(normalized.at(i).toAscii());
    if (!isalnum(current) && (current != '-') && (current != '_'))
      normalized.replace(i, 1, '-');
  }
  if (normalized.isEmpty())
    normalized = "x";
  else if (normalized.size() > max_metric_length)
    normalized.resize(max_metric_length);
  if (!isalnum(normalized.at(0).toLatin1()))
    normalized.replace(0, 1, 'x');
  return (normalized);
}

/**
 *  Open a RRD file which already exists.
 *
 *  @param[in] filename Path to the RRD file.
 *  @param[in] metric   Metric name.
 */
void lib::open(QString const& filename,
               QString const& metric) {
  // Close previous file.
  this->close();

  // Check that the file exists.
  if (!QFile::exists(filename))
    throw (exceptions::open() << "RRD: file '"
             << filename << "' does not exist");

  // Remember information for further operations.
  _filename = filename;
  _metric = normalize_metric_name(metric);

  return ;
}

/**
 *  Open a RRD file and create it if it does not exists.
 *
 *  @param[in] filename Path to the RRD file.
 *  @param[in] metric   Metric name.
 *  @param[in] length   Number of recording in the RRD file.
 *  @param[in] from     Timestamp of the first record.
 *  @param[in] interval Time interval between each record.
 */
void lib::open(QString const& filename,
               QString const& metric,
               unsigned int length,
               time_t from,
               time_t interval) {
  // Close previous file.
  this->close();

  // Remember informations for further operations.
  _filename = filename;
  _metric = normalize_metric_name(metric);

  /* Find step of RRD file if already existing. */
  /* XXX : why is it here ?
  rrd_info_t* rrdinfo(rrd_info_r(_filename));
  time_t interval_offset(0);
  for (rrd_info_t* tmp = rrdinfo; tmp; tmp = tmp->next)
    if (!strcmp(rrdinfo->key, "step"))
      if (interval < static_cast<time_t>(rrdinfo->value.u_cnt))
        interval_offset = rrdinfo->value.u_cnt / interval - 1;
  rrd_info_free(rrdinfo);
  */

  /* Remove previous file. */
  QFile::remove(_filename);

  /* Set parameters. */
  std::ostringstream ds_oss;
  std::ostringstream rra1_oss;
  std::ostringstream rra2_oss;
  ds_oss << "DS:" << _metric.toStdString() << ":GAUGE:" << interval << ":U:U";
  rra1_oss << "RRA:AVERAGE:0.5:1:" << length;
  rra2_oss << "RRA:AVERAGE:0.5:12:" << length / 12;
  std::string ds(ds_oss.str());
  std::string rra1(rra1_oss.str());
  std::string rra2(rra2_oss.str());
  char const* argv[5];
  argv[0] = ds.c_str();
  argv[1] = rra1.c_str();
  argv[2] = rra2.c_str();
  argv[3] = NULL;

  // Debug message.
  logging::debug << logging::HIGH << "RRD: opening file '" << filename
    << "' (" << argv[0] << ", " << argv[1] << ", " << argv[2]
    << ", interval " << interval << ", from " << from << ")";

  // Create RRD file.
  rrd_clear_error();
  if (rrd_create_r(_filename.toStdString().c_str(),
        interval,
        from,
        3,
        argv))
    throw (exceptions::open() << "RRD: could not create file '"
             << _filename << "': " << rrd_get_error());

  // Set parameters.
  std::string fn(_filename.toStdString());
  std::string hb;
  {
    std::ostringstream oss;
    oss << qPrintable(_metric) << ":" << interval * 10;
    hb = oss.str();
  }
  argv[0] = "librrd";
  argv[1] = fn.c_str();
  argv[2] = "-h"; // --heartbeat
  argv[3] = hb.c_str();
  argv[4] = NULL;

  // Tune file.
  if (rrd_tune(4, (char**)argv))
    logging::error << logging::MEDIUM << "RRD: could not tune "\
      "heartbeat of file '" << _filename << "'";

  return ;
}

/**
 *  Update the RRD file with new value.
 *
 *  @param[in] t     Timestamp of value.
 *  @param[in] value Associated value.
 */
void lib::update(time_t t, QString const& value) {
  // Build argument string.
  std::string arg;
  {
    std::ostringstream oss;
    oss << t << ":" << value.toStdString();
    arg = oss.str();
  }

  // Set argument table.
  char const* argv[2];
  argv[0] = arg.c_str();
  argv[1] = NULL;

  // Debug message.
  logging::debug << logging::HIGH << "RRD: updating file '"
    << _filename << "' (metric '" << _metric << "', " << argv[0] << ")";

  // Update RRD file.
  int fd(::open(_filename.toStdString().c_str(), O_WRONLY));
  if (fd < 0) {
    char const* msg(strerror(errno));
    logging::error << logging::MEDIUM << "RRD: could not open file '"
      << _filename << "': " << msg;
  }
  else {
    try {
      // Set lock.
      struct flock fl;
      memset(&fl, 0, sizeof(fl));
      fl.l_type = F_WRLCK;
      fl.l_whence = SEEK_SET;
      if (-1 == fcntl(fd, F_SETLK, &fl)) {
        char const* msg(strerror(errno));
        logging::error << logging::MEDIUM << "RRD: could not lock file '"
          << _filename << "': " << msg;
      }
      else {
        rrd_clear_error();
        if (rrd_update_r(_filename.toStdString().c_str(),
              _metric.toStdString().c_str(),
              sizeof(argv) / sizeof(*argv) - 1,
              argv))
          throw (exceptions::update()
                   << "RRD: failed to update value for metric "
                   << _metric << ": " << rrd_get_error());
      }
    }
    catch (...) {
      ::close(fd);
      throw ;
    }
    ::close(fd);
  }

  return ;
}
<commit_msg>Do not change first character of RRD DS name if it is a '-' or a '_'.<commit_after>/*
** Copyright 2011-2012 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <QFile>
#include <rrd.h>
#include <sstream>
#include <string.h>
#include <unistd.h>
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/rrd/exceptions/open.hh"
#include "com/centreon/broker/rrd/exceptions/update.hh"
#include "com/centreon/broker/rrd/lib.hh"

using namespace com::centreon::broker;
using namespace com::centreon::broker::rrd;

/**************************************
*                                     *
*           Public Methods            *
*                                     *
**************************************/

/**
 *  Default constructor.
 */
lib::lib() {}

/**
 *  Copy constructor.
 *
 *  @param[in] l Object to copy.
 */
lib::lib(lib const& l)
  : backend(l), _filename(l._filename), _metric(l._metric) {}

/**
 *  Destructor.
 */
lib::~lib() {}

/**
 *  Assignment operator.
 *
 *  @param[in] l Object to copy.
 *
 *  @return This object.
 */
lib& lib::operator=(lib const& l) {
  backend::operator=(l);
  _filename = l._filename;
  _metric = l._metric;
  return (*this);
}

/**
 *  @brief Initiates the bulk load of multiple commands.
 *
 *  With the librrd backend, this method does nothing.
 */
void lib::begin() {
  return ;
}

/**
 *  Close the RRD file.
 */
void lib::close() {
  _filename.clear();
  _metric.clear();
  return ;
}

/**
 *  @brief Commit transaction started with begin().
 *
 *  With the librrd backend, the method does nothing.
 */
void lib::commit() {
  return ;
}

/**
 *  Normalize a metric name.
 *
 *  @param[in] metric Metric name.
 *
 *  @return Normalized metric name.
 */
QString lib::normalize_metric_name(QString const& metric) {
  QString normalized(metric.toLatin1());
  normalized.replace("/", "slash_");
  normalized.replace("#S#", "slash_");
  normalized.replace("\\", "bslash_");
  normalized.replace("#BS#", "bslash_");
  normalized.replace("%", "pct_");
  normalized.replace("#P#", "pct_");
  for (unsigned int i(0), size(normalized.size()); i < size; ++i) {
    char current(normalized.at(i).toAscii());
    if (!isalnum(current) && (current != '-') && (current != '_'))
      normalized.replace(i, 1, '-');
  }
  if (normalized.isEmpty())
    normalized = "x";
  else if (normalized.size() > max_metric_length)
    normalized.resize(max_metric_length);
  return (normalized);
}

/**
 *  Open a RRD file which already exists.
 *
 *  @param[in] filename Path to the RRD file.
 *  @param[in] metric   Metric name.
 */
void lib::open(QString const& filename,
               QString const& metric) {
  // Close previous file.
  this->close();

  // Check that the file exists.
  if (!QFile::exists(filename))
    throw (exceptions::open() << "RRD: file '"
             << filename << "' does not exist");

  // Remember information for further operations.
  _filename = filename;
  _metric = normalize_metric_name(metric);

  return ;
}

/**
 *  Open a RRD file and create it if it does not exists.
 *
 *  @param[in] filename Path to the RRD file.
 *  @param[in] metric   Metric name.
 *  @param[in] length   Number of recording in the RRD file.
 *  @param[in] from     Timestamp of the first record.
 *  @param[in] interval Time interval between each record.
 */
void lib::open(QString const& filename,
               QString const& metric,
               unsigned int length,
               time_t from,
               time_t interval) {
  // Close previous file.
  this->close();

  // Remember informations for further operations.
  _filename = filename;
  _metric = normalize_metric_name(metric);

  /* Find step of RRD file if already existing. */
  /* XXX : why is it here ?
  rrd_info_t* rrdinfo(rrd_info_r(_filename));
  time_t interval_offset(0);
  for (rrd_info_t* tmp = rrdinfo; tmp; tmp = tmp->next)
    if (!strcmp(rrdinfo->key, "step"))
      if (interval < static_cast<time_t>(rrdinfo->value.u_cnt))
        interval_offset = rrdinfo->value.u_cnt / interval - 1;
  rrd_info_free(rrdinfo);
  */

  /* Remove previous file. */
  QFile::remove(_filename);

  /* Set parameters. */
  std::ostringstream ds_oss;
  std::ostringstream rra1_oss;
  std::ostringstream rra2_oss;
  ds_oss << "DS:" << _metric.toStdString() << ":GAUGE:" << interval << ":U:U";
  rra1_oss << "RRA:AVERAGE:0.5:1:" << length;
  rra2_oss << "RRA:AVERAGE:0.5:12:" << length / 12;
  std::string ds(ds_oss.str());
  std::string rra1(rra1_oss.str());
  std::string rra2(rra2_oss.str());
  char const* argv[5];
  argv[0] = ds.c_str();
  argv[1] = rra1.c_str();
  argv[2] = rra2.c_str();
  argv[3] = NULL;

  // Debug message.
  logging::debug << logging::HIGH << "RRD: opening file '" << filename
    << "' (" << argv[0] << ", " << argv[1] << ", " << argv[2]
    << ", interval " << interval << ", from " << from << ")";

  // Create RRD file.
  rrd_clear_error();
  if (rrd_create_r(_filename.toStdString().c_str(),
        interval,
        from,
        3,
        argv))
    throw (exceptions::open() << "RRD: could not create file '"
             << _filename << "': " << rrd_get_error());

  // Set parameters.
  std::string fn(_filename.toStdString());
  std::string hb;
  {
    std::ostringstream oss;
    oss << qPrintable(_metric) << ":" << interval * 10;
    hb = oss.str();
  }
  argv[0] = "librrd";
  argv[1] = fn.c_str();
  argv[2] = "-h"; // --heartbeat
  argv[3] = hb.c_str();
  argv[4] = NULL;

  // Tune file.
  if (rrd_tune(4, (char**)argv))
    logging::error << logging::MEDIUM << "RRD: could not tune "\
      "heartbeat of file '" << _filename << "'";

  return ;
}

/**
 *  Update the RRD file with new value.
 *
 *  @param[in] t     Timestamp of value.
 *  @param[in] value Associated value.
 */
void lib::update(time_t t, QString const& value) {
  // Build argument string.
  std::string arg;
  {
    std::ostringstream oss;
    oss << t << ":" << value.toStdString();
    arg = oss.str();
  }

  // Set argument table.
  char const* argv[2];
  argv[0] = arg.c_str();
  argv[1] = NULL;

  // Debug message.
  logging::debug << logging::HIGH << "RRD: updating file '"
    << _filename << "' (metric '" << _metric << "', " << argv[0] << ")";

  // Update RRD file.
  int fd(::open(_filename.toStdString().c_str(), O_WRONLY));
  if (fd < 0) {
    char const* msg(strerror(errno));
    logging::error << logging::MEDIUM << "RRD: could not open file '"
      << _filename << "': " << msg;
  }
  else {
    try {
      // Set lock.
      struct flock fl;
      memset(&fl, 0, sizeof(fl));
      fl.l_type = F_WRLCK;
      fl.l_whence = SEEK_SET;
      if (-1 == fcntl(fd, F_SETLK, &fl)) {
        char const* msg(strerror(errno));
        logging::error << logging::MEDIUM << "RRD: could not lock file '"
          << _filename << "': " << msg;
      }
      else {
        rrd_clear_error();
        if (rrd_update_r(_filename.toStdString().c_str(),
              _metric.toStdString().c_str(),
              sizeof(argv) / sizeof(*argv) - 1,
              argv))
          throw (exceptions::update()
                   << "RRD: failed to update value for metric "
                   << _metric << ": " << rrd_get_error());
      }
    }
    catch (...) {
      ::close(fd);
      throw ;
    }
    ::close(fd);
  }

  return ;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: filebuff.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: np $ $Date: 2002-08-08 16:08:17 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "filebuff.hxx"

#include <string.h>
#include <fstream>
#include <ctype.h>

bool
LoadXmlFile( Buffer &           o_rBuffer,
             const char *       i_sXmlFilePath )
{
    std::ifstream aXmlFile;

    aXmlFile.open(i_sXmlFilePath, std::ios::in
#ifdef WNT
                                          | std::ios::binary
#endif // WNT
    );

    if (! aXmlFile)
        return false;

    // Prepare buffer:
    aXmlFile.seekg(0, std::ios::end);
    unsigned long nBufferSize = aXmlFile.tellg();
    o_rBuffer.SetSize(nBufferSize + 1);
    o_rBuffer.Data()[nBufferSize] = '\0';
    aXmlFile.seekg(0);

    // Read file:
    aXmlFile.read(o_rBuffer.Data(), nBufferSize);
    bool ret = aXmlFile.good() != 0;
    aXmlFile.close();
    return ret;
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.6.92); FILE MERGED 2005/09/05 14:47:39 rt 1.6.92.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: filebuff.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 12:02:26 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "filebuff.hxx"

#include <string.h>
#include <fstream>
#include <ctype.h>

bool
LoadXmlFile( Buffer &           o_rBuffer,
             const char *       i_sXmlFilePath )
{
    std::ifstream aXmlFile;

    aXmlFile.open(i_sXmlFilePath, std::ios::in
#ifdef WNT
                                          | std::ios::binary
#endif // WNT
    );

    if (! aXmlFile)
        return false;

    // Prepare buffer:
    aXmlFile.seekg(0, std::ios::end);
    unsigned long nBufferSize = aXmlFile.tellg();
    o_rBuffer.SetSize(nBufferSize + 1);
    o_rBuffer.Data()[nBufferSize] = '\0';
    aXmlFile.seekg(0);

    // Read file:
    aXmlFile.read(o_rBuffer.Data(), nBufferSize);
    bool ret = aXmlFile.good() != 0;
    aXmlFile.close();
    return ret;
}

<|endoftext|>


<commit_before>
// vim:sw=2:ai

/*
 * Copyright (C) 2010 DeNA Co.,Ltd.. All rights reserved.
 * See COPYRIGHT.txt for details.
 */

#ifndef DENA_MYSQL_INCL_HPP
#define DENA_MYSQL_INCL_HPP

#ifndef HAVE_CONFIG_H
#define HAVE_CONFIG_H
#endif

#define MYSQL_DYNAMIC_PLUGIN
#define MYSQL_SERVER 1

#include <my_config.h>
#ifdef DBUG_ON
#define SAFE_MUTEX
#endif

#include <mysql_version.h>

#if MYSQL_VERSION_ID >= 50505
#include <my_pthread.h>
#include <sql_priv.h>
#include "sql_class.h"
#include "unireg.h"
#include "lock.h"
#include "key.h" // key_copy()
#include <my_global.h>
#include <mysql/plugin.h>
#include <transaction.h>
#include <sql_base.h>
#define safeFree(X) my_free(X)
#define pthread_cond_timedwait  mysql_cond_timedwait
#define  pthread_mutex_lock  mysql_mutex_lock
#define  pthread_mutex_unlock  mysql_mutex_unlock
#define current_stmt_binlog_row_based  is_current_stmt_binlog_format_row
#define clear_current_stmt_binlog_row_based  clear_current_stmt_binlog_format_row

#else
#include "mysql_priv.h"
#endif

#undef min
#undef max

#endif

<commit_msg>temp commit<commit_after>
// vim:sw=2:ai

/*
 * Copyright (C) 2010 DeNA Co.,Ltd.. All rights reserved.
 * See COPYRIGHT.txt for details.
 */

#ifndef DENA_MYSQL_INCL_HPP
#define DENA_MYSQL_INCL_HPP

#ifndef HAVE_CONFIG_H
#define HAVE_CONFIG_H
#endif

#define MYSQL_DYNAMIC_PLUGIN
#define MYSQL_SERVER 1

#include <my_config.h>
#ifdef DBUG_ON
#define SAFE_MUTEX
#endif

#include <mysql_version.h>

#if MYSQL_VERSION_ID >= 50505
#include <my_pthread.h>
#include <sql_priv.h>
#include "sql_class.h"
#include "unireg.h"
#include "lock.h"
#include "key.h" // key_copy()
#include <my_global.h>
#include <mysql/plugin.h>
#include <transaction.h>
#include <sql_base.h>
// FIXME FIXME FIXME
#define safeFree(X) my_free(X)
#define pthread_cond_timedwait  mysql_cond_timedwait
#define  pthread_mutex_lock  mysql_mutex_lock
#define  pthread_mutex_unlock  mysql_mutex_unlock
#define current_stmt_binlog_row_based  is_current_stmt_binlog_format_row
#define clear_current_stmt_binlog_row_based  clear_current_stmt_binlog_format_row

#else
#include "mysql_priv.h"
#endif

#undef min
#undef max

#endif

<|endoftext|>


<commit_before>/*****************************************************************************
 * vlc-libvlc-jni.cc: JNI interface for vlc Java Bindings
 *****************************************************************************
 * Copyright (C) 1998-2006 the VideoLAN team
 *
 * Authors: Filippo Carone <filippo@carone.org>
 *          Philippe Morin <phmorin@free.fr>
 *
 * $Id: core-jni.cc 156 2006-08-01 09:23:01Z littlejohn $
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
 *****************************************************************************/

/* These are a must*/
#include <jni.h>
#include <vlc/libvlc.h>

#include <stdio.h>  // for printf
#include <stdlib.h> // for calloc
#include <string.h> // for strcmp
#include <unistd.h> // for usleep

/* JVLC internal imports, generated by gcjh */
#include "../includes/JVLC.h"

#include <jawt.h>
#include <jawt_md.h>

#include "utils.h"

jlong getClassInstance (JNIEnv *env, jobject _this);

JNIEXPORT jlong JNICALL Java_org_videolan_jvlc_JVLC_createInstance (JNIEnv *env, jobject _this, jobjectArray args) {

    long res;
    int argc;
    const char **argv;

    libvlc_exception_t *exception = ( libvlc_exception_t * ) malloc( sizeof( libvlc_exception_t ) );

    libvlc_exception_init( exception );

    argc = (int) env->GetArrayLength((jarray) args);
    argv = (const char **) malloc(argc * sizeof(char*));

    for (int i = 0; i < argc; i++) {
        argv[i] = env->GetStringUTFChars((jstring) env->GetObjectArrayElement(args, i),
                                         0
        );
    }

    res = (long) libvlc_new(argc, (char**) argv, exception );

    free( exception );

    return res;

}

JNIEXPORT void JNICALL Java_org_videolan_jvlc_JVLC__1destroy (JNIEnv *env, jobject _this)
{
    long instance;

    instance = getClassInstance( env, _this );

    libvlc_destroy( (libvlc_instance_t *) instance, NULL);

    return;
}

//JNIEXPORT void JNICALL Java_org_videolan_jvlc_JVLC__1paint (JNIEnv *env, jobject _this, jobject canvas, jobject graphics)

/*
 * Utility functions
 */
jlong getClassInstance (JNIEnv *env, jobject _this) {
    /* get the id field of object */
    jclass    cls   = env->GetObjectClass(_this);
    jmethodID mid   = env->GetMethodID(cls, "getInstance", "()J");
    jlong     field = env->CallLongMethod(_this, mid);
    return field;
}
<commit_msg>Fix include for WIN32 version.<commit_after>/*****************************************************************************
 * vlc-libvlc-jni.cc: JNI interface for vlc Java Bindings
 *****************************************************************************
 * Copyright (C) 1998-2006 the VideoLAN team
 *
 * Authors: Filippo Carone <filippo@carone.org>
 *          Philippe Morin <phmorin@free.fr>
 *
 * $Id: core-jni.cc 156 2006-08-01 09:23:01Z littlejohn $
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
 *****************************************************************************/

/* These are a must*/
#include <jni.h>
#include <vlc/libvlc.h>

#include <stdio.h>  // for printf
#include <stdlib.h> // for calloc
#include <string.h> // for strcmp
#ifdef WIN32
#undef usleep
#define usleep(var) Sleep(var/1000)
#else
#include <unistd.h> // for usleep
#endif

/* JVLC internal imports, generated by gcjh */
#include "../includes/JVLC.h"

#include <jawt.h>
#include <jawt_md.h>

#include "utils.h"

jlong getClassInstance (JNIEnv *env, jobject _this);

JNIEXPORT jlong JNICALL Java_org_videolan_jvlc_JVLC_createInstance (JNIEnv *env, jobject _this, jobjectArray args) {

    long res;
    int argc;
    const char **argv;

    libvlc_exception_t *exception = ( libvlc_exception_t * ) malloc( sizeof( libvlc_exception_t ) );

    libvlc_exception_init( exception );

    argc = (int) env->GetArrayLength((jarray) args);
    argv = (const char **) malloc(argc * sizeof(char*));

    for (int i = 0; i < argc; i++) {
        argv[i] = env->GetStringUTFChars((jstring) env->GetObjectArrayElement(args, i),
                                         0
        );
    }

    res = (long) libvlc_new(argc, (char**) argv, exception );

    free( exception );

    return res;

}

JNIEXPORT void JNICALL Java_org_videolan_jvlc_JVLC__1destroy (JNIEnv *env, jobject _this)
{
    long instance;

    instance = getClassInstance( env, _this );

    libvlc_destroy( (libvlc_instance_t *) instance, NULL);

    return;
}

//JNIEXPORT void JNICALL Java_org_videolan_jvlc_JVLC__1paint (JNIEnv *env, jobject _this, jobject canvas, jobject graphics)

/*
 * Utility functions
 */
jlong getClassInstance (JNIEnv *env, jobject _this) {
    /* get the id field of object */
    jclass    cls   = env->GetObjectClass(_this);
    jmethodID mid   = env->GetMethodID(cls, "getInstance", "()J");
    jlong     field = env->CallLongMethod(_this, mid);
    return field;
}
<|endoftext|>


<commit_before>/*
    This file is part of kdepim.

    Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>

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

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

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include "kmailchanges.h"
#include "kolabconfig.h"

#include <kapplication.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kemailsettings.h>
#include <identitymanager.h>
#include <identity.h>
#include <kdebug.h>

class CreateDisconnectedImapAccount : public KConfigPropagator::Change
{
  public:
    CreateDisconnectedImapAccount()
      : KConfigPropagator::Change( i18n("Create Disconnected IMAP Account for KMail") )
    {
    }

    // This sucks as this is a 1:1 copy from KMAccount::encryptStr()
    static QString encryptStr(const QString& aStr)
    {
      QString result;
      for (uint i = 0; i < aStr.length(); i++)
        result += (aStr[i].unicode() < 0x20) ? aStr[i] :
          QChar(0x1001F - aStr[i].unicode());
      return result;

    }

    void apply()
    {
      QString email;
      QString user = KolabConfig::self()->user();
      int pos = user.find( "@" );
      // with kolab the userid _is_ the full email
      if ( pos > 0 )
        // The user typed in a full email address. Assume it's correct
        email = user;
      else
        // Construct the email address. And use it for the username also
        user = email = user+"@"+KolabConfig::self()->server();

      KConfig c( "kmailrc" );
      c.setGroup( "General" );
      c.writeEntry( "Default domain", KolabConfig::self()->server() );
      uint accCnt = c.readNumEntry( "accounts", 0 );
      c.writeEntry( "accounts", accCnt+1 );
      uint transCnt = c.readNumEntry( "transports", 0 );
      c.writeEntry( "transports", transCnt+1 );

      c.setGroup( QString("Account %1").arg(accCnt+1) );
      int uid = kapp->random();
      c.writeEntry( "Folder", uid );
      c.writeEntry( "Id", uid );
      c.writeEntry( "Type", "cachedimap");
      c.writeEntry( "auth", "*");
      c.writeEntry( "Name", "Kolab Server" );
      c.writeEntry( "host", KolabConfig::self()->server() );

      c.writeEntry( "login", user );

      if ( KolabConfig::self()->savePassword() ) {
        c.writeEntry( "pass", encryptStr(KolabConfig::self()->password()) );
        c.writeEntry( "store-passwd", true );
      }
      c.writeEntry( "port", "993" );
      c.writeEntry( "use-ssl", true );

      c.writeEntry( "sieve-support", "true" );

      c.setGroup( QString("Folder-%1").arg( uid ) );
      c.writeEntry( "isOpen", true );

      c.setGroup( QString("Transport %1").arg(transCnt+1) );
      c.writeEntry( "name", "Kolab Server" );
      c.writeEntry( "host", KolabConfig::self()->server() );
      c.writeEntry( "type", "smtp" );
      c.writeEntry( "port", "465" );
      c.writeEntry( "encryption", "SSL" );
      c.writeEntry( "auth", true );
      c.writeEntry( "authtype", "PLAIN" );
      c.writeEntry( "user", email );
      c.writeEntry( "pass", encryptStr(KolabConfig::self()->password()) );
      c.writeEntry( "storepass", "true" );

      // Write email in "default kcontrol settings", used by IdentityManager
      // if it has to create a default identity.
      KEMailSettings es;
      es.setSetting( KEMailSettings::RealName, KolabConfig::self()->realName() );
      es.setSetting( KEMailSettings::EmailAddress, email );
      es.setSetting( KEMailSettings::ClientProgram, "kontact" );

      KPIM::IdentityManager identityManager;
      if ( !identityManager.allEmails().contains( email ) ) {
        // Not sure how to name the identity. First one is "Default", next one "Kolab", but then...
        KPIM::Identity& identity = identityManager.newFromScratch( i18n( "Kolab" ) );
        identity.setFullName( KolabConfig::self()->realName() );
        identity.setEmailAddr( email );
        identityManager.commit();
      }

      // This needs to be done here, since it reference just just generated id
      c.setGroup( "IMAP Resource" );
      c.writeEntry("TheIMAPResourceAccount", uid);
      c.writeEntry("TheIMAPResourceFolderParent", QString(".%1.directory/INBOX").arg( uid ));
   }

};

void createKMailChanges( KConfigPropagator::Change::List& changes )
{
  KConfigPropagator::ChangeConfig *c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "Groupware";
  c->name = "Enabled";
  c->value = "true";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "Groupware";
  c->name = "AutoAccept";
  c->value = "false";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "Groupware";
  c->name = "AutoDeclConflict";
  c->value = "false";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "Groupware";
  c->name = "LegacyMangleFromToHeaders";
  c->value = "true";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "Groupware";
  c->name = "LegacyBodyInvites";
  c->value = "true";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "IMAP Resource";
  c->name = "Enabled";
  c->value = "true";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "IMAP Resource";
  c->name = "TheIMAPResourceEnabled";
  c->value = "true";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "IMAP Resource";
  c->name = "TheIMAPResourceStorageFormat";
  c->value = "XML";
  changes.append( c );

  changes.append( new CreateDisconnectedImapAccount );
}
<commit_msg>Take the domain from the emailaddress if it looks like user@domain, as requested in https://intevation.de/roundup/kolab/issue522<commit_after>/*
    This file is part of kdepim.

    Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>

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

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

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include "kmailchanges.h"
#include "kolabconfig.h"

#include <kapplication.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kemailsettings.h>
#include <identitymanager.h>
#include <identity.h>
#include <kdebug.h>

class CreateDisconnectedImapAccount : public KConfigPropagator::Change
{
  public:
    CreateDisconnectedImapAccount()
      : KConfigPropagator::Change( i18n("Create Disconnected IMAP Account for KMail") )
    {
    }

    // This sucks as this is a 1:1 copy from KMAccount::encryptStr()
    static QString encryptStr(const QString& aStr)
    {
      QString result;
      for (uint i = 0; i < aStr.length(); i++)
        result += (aStr[i].unicode() < 0x20) ? aStr[i] :
          QChar(0x1001F - aStr[i].unicode());
      return result;

    }

    void apply()
    {
      QString defaultDomain = KolabConfig::self()->server();
      QString email;
      QString user = KolabConfig::self()->user();
      int pos = user.find( "@" );
      // with kolab the userid _is_ the full email
      if ( pos > 0 ) {
        // The user typed in a full email address. Assume it's correct
        email = user;
        const QString h = user.mid( pos+1 );
        if ( !h.isEmpty() )
          // The user did type in a domain on the email address. Use that
          defaultDomain = h;
      }
      else
        // Construct the email address. And use it for the username also
        user = email = user+"@"+KolabConfig::self()->server();

      KConfig c( "kmailrc" );
      c.setGroup( "General" );
      c.writeEntry( "Default domain", defaultDomain );
      uint accCnt = c.readNumEntry( "accounts", 0 );
      c.writeEntry( "accounts", accCnt+1 );
      uint transCnt = c.readNumEntry( "transports", 0 );
      c.writeEntry( "transports", transCnt+1 );

      c.setGroup( QString("Account %1").arg(accCnt+1) );
      int uid = kapp->random();
      c.writeEntry( "Folder", uid );
      c.writeEntry( "Id", uid );
      c.writeEntry( "Type", "cachedimap");
      c.writeEntry( "auth", "*");
      c.writeEntry( "Name", "Kolab Server" );
      c.writeEntry( "host", KolabConfig::self()->server() );

      c.writeEntry( "login", user );

      if ( KolabConfig::self()->savePassword() ) {
        c.writeEntry( "pass", encryptStr(KolabConfig::self()->password()) );
        c.writeEntry( "store-passwd", true );
      }
      c.writeEntry( "port", "993" );
      c.writeEntry( "use-ssl", true );

      c.writeEntry( "sieve-support", "true" );

      c.setGroup( QString("Folder-%1").arg( uid ) );
      c.writeEntry( "isOpen", true );

      c.setGroup( QString("Transport %1").arg(transCnt+1) );
      c.writeEntry( "name", "Kolab Server" );
      c.writeEntry( "host", KolabConfig::self()->server() );
      c.writeEntry( "type", "smtp" );
      c.writeEntry( "port", "465" );
      c.writeEntry( "encryption", "SSL" );
      c.writeEntry( "auth", true );
      c.writeEntry( "authtype", "PLAIN" );
      c.writeEntry( "user", email );
      c.writeEntry( "pass", encryptStr(KolabConfig::self()->password()) );
      c.writeEntry( "storepass", "true" );

      // Write email in "default kcontrol settings", used by IdentityManager
      // if it has to create a default identity.
      KEMailSettings es;
      es.setSetting( KEMailSettings::RealName, KolabConfig::self()->realName() );
      es.setSetting( KEMailSettings::EmailAddress, email );
      es.setSetting( KEMailSettings::ClientProgram, "kontact" );

      KPIM::IdentityManager identityManager;
      if ( !identityManager.allEmails().contains( email ) ) {
        // Not sure how to name the identity. First one is "Default", next one "Kolab", but then...
        KPIM::Identity& identity = identityManager.newFromScratch( i18n( "Kolab" ) );
        identity.setFullName( KolabConfig::self()->realName() );
        identity.setEmailAddr( email );
        identityManager.commit();
      }

      // This needs to be done here, since it reference just just generated id
      c.setGroup( "IMAP Resource" );
      c.writeEntry("TheIMAPResourceAccount", uid);
      c.writeEntry("TheIMAPResourceFolderParent", QString(".%1.directory/INBOX").arg( uid ));
   }

};

void createKMailChanges( KConfigPropagator::Change::List& changes )
{
  KConfigPropagator::ChangeConfig *c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "Groupware";
  c->name = "Enabled";
  c->value = "true";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "Groupware";
  c->name = "AutoAccept";
  c->value = "false";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "Groupware";
  c->name = "AutoDeclConflict";
  c->value = "false";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "Groupware";
  c->name = "LegacyMangleFromToHeaders";
  c->value = "true";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "Groupware";
  c->name = "LegacyBodyInvites";
  c->value = "true";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "IMAP Resource";
  c->name = "Enabled";
  c->value = "true";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "IMAP Resource";
  c->name = "TheIMAPResourceEnabled";
  c->value = "true";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "IMAP Resource";
  c->name = "TheIMAPResourceStorageFormat";
  c->value = "XML";
  changes.append( c );

  changes.append( new CreateDisconnectedImapAccount );
}
<|endoftext|>


<commit_before>#include <cmath>
#include <iostream>
#include <vector>

using namespace std;

inline void use_io_optimizations()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
}

template <typename T>
class StaticRmq
{
public:
    StaticRmq(const vector<T>& array):
        ranges(array.size(), vector<T>(log2(array.size()) + 1))
    {
        typename vector<T>::size_type n = array.size();

        for (typename vector<T>::size_type i = 0; i < n; ++i)
        {
            ranges[i][0] = array[i];
        }

        for (typename vector<T>::size_type j = 1; (1 << j) <= n; ++j)
        {
            for (typename vector<T>::size_type i = 0; i + (1 << j) - 1 < n; ++i)
            {
                if (ranges[i][j - 1] > ranges[i + (1 << (j - 1))][j - 1])
                {
                    ranges[i][j] = ranges[i][j - 1];
                }
                else
                {
                    ranges[i][j] = ranges[i + (1 << (j - 1))][j - 1];
                }
            }
        }
    }

    T query(unsigned int left, unsigned int right) const
    {
        unsigned int k = log2(right - left + 1);

        if (ranges[left][k] >= ranges[right - (1 << k) + 1][k])
        {
            return ranges[left][k];
        }
        else
        {
            return ranges[right - (1 << k) + 1][k];
        }
    }

private:
    vector< vector<T> > ranges;
};

void read_input(unsigned int& elements_count,
                vector<unsigned int>& elements,
                unsigned int& subarray_size)
{
    cin >> elements_count;

    elements = vector<unsigned int>(elements_count);

    for (unsigned int i = 0; i < elements_count; ++i)
    {
        cin >> elements[i];
    }

    cin >> subarray_size;
}

void write_output(unsigned int elements_count,
                  unsigned int subarray_size,
                  const StaticRmq<unsigned int>& rmq)
{
    for (unsigned int i = 0; i < elements_count - subarray_size + 1; ++i)
    {
        cout << rmq.query(i, i + subarray_size - 1);

        if (i < elements_count - 1)
        {
            cout << ' ';
        }
    }

    cout << '\n';
}

int main()
{
    use_io_optimizations();

    unsigned int         elements_count;
    vector<unsigned int> elements;
    unsigned int         subarray_size;

    read_input(elements_count, elements, subarray_size);

    StaticRmq<unsigned int> rmq(elements);

    write_output(elements_count, subarray_size, rmq);

    return 0;
}
<commit_msg>spoj; improve the solution to "subarrays"<commit_after>#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>

using namespace std;

inline void use_io_optimizations()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
}

class StaticRmq
{
public:
    StaticRmq(const vector<unsigned int>& array):
        ranges(array.size(), vector<unsigned int>(log2(array.size()) + 1))
    {
        typedef vector<unsigned int>::size_type index;

        index n = array.size();

        for (index i = 0; i < n; ++i)
        {
            ranges[i][0] = array[i];
        }

        for (index j = 1; (1 << j) <= n; ++j)
        {
            for (index i = 0; i + (1 << j) - 1 < n; ++i)
            {
                ranges[i][j] = max(ranges[i][j - 1],
                                   ranges[i + (1 << (j - 1))][j - 1]);
            }
        }
    }

    unsigned int get(unsigned int left, unsigned int right) const
    {
        unsigned int k = log2(right - left + 1);

        return max(ranges[left][k], ranges[right - (1 << k) + 1][k]);
    }

private:
    vector< vector<unsigned int> > ranges;
};

void read_input(unsigned int& elements_count,
                vector<unsigned int>& elements,
                unsigned int& subarray_size)
{
    cin >> elements_count;
    elements = vector<unsigned int>(elements_count);

    for (unsigned int i = 0; i < elements_count; ++i)
    {
        cin >> elements[i];
    }

    cin >> subarray_size;
}

void write_output(unsigned int elements_count,
                  unsigned int subarray_size,
                  const StaticRmq& rmq)
{
    for (unsigned int i = 0; i < elements_count - subarray_size + 1; ++i)
    {
        cout << rmq.get(i, i + subarray_size - 1);

        if (i < elements_count - 1)
        {
            cout << ' ';
        }
    }

    cout << '\n';
}

int main()
{
    use_io_optimizations();

    unsigned int         elements_count;
    vector<unsigned int> elements;
    unsigned int         subarray_size;

    read_input(elements_count, elements, subarray_size);

    StaticRmq rmq(elements);

    write_output(elements_count, subarray_size, rmq);

    return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#include "../general/forall.hpp"
#include "bilininteg.hpp"
#include "gridfunc.hpp"
#include "../linalg/elementmatrix.hpp"

namespace mfem
{

static void EADGTraceAssemble1D(const int NF,
                                const Array<double> &basis,
                                const Vector &padata,
                                Vector &eadata_int,
                                Vector &eadata_ext)
{
   auto D = Reshape(padata.Read(), 2, 2, NF);
   auto A_int = Reshape(eadata_int.Write(), 2, NF);
   auto A_ext = Reshape(eadata_ext.Write(), 2, NF);
   MFEM_FORALL(f, NF,
   {
      double val_int0  = D(0, 0, f);
      double val_int1  = D(1, 1, f);
      double val_ext01 = D(1, 0, f);
      double val_ext10 = D(0, 1, f);
      A_int(0, f) = val_int0;
      A_int(1, f) = val_int1;
      A_ext(0, f) = val_ext01;
      A_ext(1, f) = val_ext10;
   });
}

template<int T_D1D = 0, int T_Q1D = 0>
static void EADGTraceAssemble2D(const int NF,
                                const Array<double> &basis,
                                const Vector &padata,
                                Vector &eadata_int,
                                Vector &eadata_ext,
                                const int d1d = 0,
                                const int q1d = 0)
{
   const int D1D = T_D1D ? T_D1D : d1d;
   const int Q1D = T_Q1D ? T_Q1D : q1d;
   MFEM_VERIFY(D1D <= MAX_D1D, "");
   MFEM_VERIFY(Q1D <= MAX_Q1D, "");
   auto B = Reshape(basis.Read(), Q1D, D1D);
   auto D = Reshape(padata.Read(), Q1D, 2, 2, NF);
   auto A_int = Reshape(eadata_int.Write(), D1D, D1D, 2, NF);
   auto A_ext = Reshape(eadata_ext.Write(), D1D, D1D, 2, NF);
   MFEM_FORALL_3D(f, NF, D1D, D1D, 1,
   {
      const int D1D = T_D1D ? T_D1D : d1d;
      const int Q1D = T_Q1D ? T_Q1D : q1d;
      constexpr int MQ1 = T_Q1D ? T_Q1D : MAX_Q1D;
      double r_Bi[MQ1];
      double r_Bj[MQ1];
      for (int q = 0; q < Q1D; q++)
      {
         r_Bi[q] = B(q,MFEM_THREAD_ID(x));
         r_Bj[q] = B(q,MFEM_THREAD_ID(y));
      }
      MFEM_FOREACH_THREAD(i1,x,D1D)
      {
         MFEM_FOREACH_THREAD(j1,y,D1D)
         {
            double val_int0 = 0.0;
            double val_int1 = 0.0;
            double val_ext01 = 0.0;
            double val_ext10 = 0.0;
            for (int k1 = 0; k1 < Q1D; ++k1)
            {
               val_int0  += r_Bi[k1] * r_Bj[k1] * D(k1, 0, 0, f);
               val_int1  += r_Bi[k1] * r_Bj[k1] * D(k1, 1, 1, f);
               val_ext01 += r_Bi[k1] * r_Bj[k1] * D(k1, 1, 0, f);
               val_ext10 += r_Bi[k1] * r_Bj[k1] * D(k1, 0, 1, f);
            }
            A_int(i1, j1, 0, f) = val_int0;
            A_int(i1, j1, 1, f) = val_int1;
            A_ext(i1, j1, 0, f) = val_ext01;
            A_ext(i1, j1, 1, f) = val_ext10;
         }
      }
   });
}

template<int T_D1D = 0, int T_Q1D = 0>
static void EADGTraceAssemble3D(const int NF,
                                const Array<double> &basis,
                                const Vector &padata,
                                Vector &eadata_int,
                                Vector &eadata_ext,
                                const int d1d = 0,
                                const int q1d = 0)
{
   const int D1D = T_D1D ? T_D1D : d1d;
   const int Q1D = T_Q1D ? T_Q1D : q1d;
   MFEM_VERIFY(D1D <= MAX_D1D, "");
   MFEM_VERIFY(Q1D <= MAX_Q1D, "");
   auto B = Reshape(basis.Read(), Q1D, D1D);
   auto D = Reshape(padata.Read(), Q1D, Q1D, 2, 2, NF);
   auto A_int = Reshape(eadata_int.Write(), D1D, D1D, D1D, D1D, 2, NF);
   auto A_ext = Reshape(eadata_ext.Write(), D1D, D1D, D1D, D1D, 2, NF);
   MFEM_FORALL_3D(f, NF, D1D, D1D, 1,
   {
      const int D1D = T_D1D ? T_D1D : d1d;
      const int Q1D = T_Q1D ? T_Q1D : q1d;
      constexpr int MD1 = T_D1D ? T_D1D : MAX_D1D;
      constexpr int MQ1 = T_Q1D ? T_Q1D : MAX_Q1D;
      double r_B[MQ1][MD1];
      for (int d = 0; d < D1D; d++)
      {
         for (int q = 0; q < Q1D; q++)
         {
            r_B[q][d] = B(q,d);
         }
      }
      MFEM_SHARED double s_D[MQ1][MQ1][2][2];
      for (int i; i < 2; i++)
      {
         for (int j; j < 2; j++)
         {
            MFEM_FOREACH_THREAD(k1,x,Q1D)
            {
               MFEM_FOREACH_THREAD(k2,y,Q1D)
               {
                  s_D[k1][k2][i][j] = D(k1,k2,i,j,f);
               }
            }
         }
      }
      MFEM_SYNC_THREAD;
      MFEM_FOREACH_THREAD(i1,x,D1D)
      {
         MFEM_FOREACH_THREAD(i2,y,D1D)
         {
            for (int j1 = 0; j1 < D1D; ++j1)
            {
               for (int j2 = 0; j2 < D1D; ++j2)
               {
                  double val_int0 = 0.0;
                  double val_int1 = 0.0;
                  double val_ext01 = 0.0;
                  double val_ext10 = 0.0;
                  for (int k1 = 0; k1 < Q1D; ++k1)
                  {
                     for (int k2 = 0; k2 < Q1D; ++k2)
                     {
                        val_int0 += r_B[k1][i1] * r_B[k1][j1]
                                  * r_B[k2][i2] * r_B[k2][j2]
                                  * s_D[k1][k2][0][0];
                        val_int1 += r_B[k1][i1] * r_B[k1][j1]
                                  * r_B[k2][i2] * r_B[k2][j2]
                                  * s_D[k1][k2][1][1];
                        val_ext01+= r_B[k1][i1] * r_B[k1][j1]
                                  * r_B[k2][i2] * r_B[k2][j2]
                                  * s_D[k1][k2][1][0];
                        val_ext10+= r_B[k1][i1] * r_B[k1][j1]
                                  * r_B[k2][i2] * r_B[k2][j2]
                                  * s_D[k1][k2][0][1];
                     }
                  }
                  A_int(i1, i2, j1, j2, 0, f) = val_int0;
                  A_int(i1, i2, j1, j2, 1, f) = val_int1;
                  A_ext(i1, i2, j1, j2, 0, f) = val_ext01;
                  A_ext(i1, i2, j1, j2, 1, f) = val_ext10;
               }
            }
         }
      }
   });
}

void DGTraceIntegrator::SetupEA(const FiniteElementSpace &fes,
                                Vector &ea_data_int,
                                Vector &ea_data_ext,
                                FaceType type)
{
   SetupPA(fes, type);
   nf = fes.GetNFbyType(type);
   const Array<double> &B = maps->B;
   if (dim == 1)
   {
      return EADGTraceAssemble1D(nf,B,pa_data,ea_data_int,ea_data_ext);
   }
   else if (dim == 2)
   {
      switch ((dofs1D << 4 ) | quad1D)
      {
         case 0x22: return EADGTraceAssemble2D<2,2>(nf,B,pa_data,ea_data_int,ea_data_ext);
         case 0x33: return EADGTraceAssemble2D<3,3>(nf,B,pa_data,ea_data_int,ea_data_ext);
         case 0x44: return EADGTraceAssemble2D<4,4>(nf,B,pa_data,ea_data_int,ea_data_ext);
         case 0x55: return EADGTraceAssemble2D<5,5>(nf,B,pa_data,ea_data_int,ea_data_ext);
         case 0x66: return EADGTraceAssemble2D<6,6>(nf,B,pa_data,ea_data_int,ea_data_ext);
         case 0x77: return EADGTraceAssemble2D<7,7>(nf,B,pa_data,ea_data_int,ea_data_ext);
         case 0x88: return EADGTraceAssemble2D<8,8>(nf,B,pa_data,ea_data_int,ea_data_ext);
         case 0x99: return EADGTraceAssemble2D<9,9>(nf,B,pa_data,ea_data_int,ea_data_ext);
         default:   return EADGTraceAssemble2D(nf,B,pa_data,ea_data_int,ea_data_ext,dofs1D,quad1D);
      }
   }
   else if (dim == 3)
   {
      switch ((dofs1D << 4 ) | quad1D)
      {
         case 0x23: return EADGTraceAssemble3D<2,3>(nf,B,pa_data,ea_data_int,ea_data_ext);
         case 0x34: return EADGTraceAssemble3D<3,4>(nf,B,pa_data,ea_data_int,ea_data_ext);
         case 0x45: return EADGTraceAssemble3D<4,5>(nf,B,pa_data,ea_data_int,ea_data_ext);
         case 0x56: return EADGTraceAssemble3D<5,6>(nf,B,pa_data,ea_data_int,ea_data_ext);
         case 0x67: return EADGTraceAssemble3D<6,7>(nf,B,pa_data,ea_data_int,ea_data_ext);
         case 0x78: return EADGTraceAssemble3D<7,8>(nf,B,pa_data,ea_data_int,ea_data_ext);
         case 0x89: return EADGTraceAssemble3D<8,9>(nf,B,pa_data,ea_data_int,ea_data_ext);
         default:   return EADGTraceAssemble3D(nf,B,pa_data,ea_data_int,ea_data_ext,dofs1D,quad1D);
      }
   }
   MFEM_ABORT("Unknown kernel.");
}

void DGTraceIntegrator::AssembleEAInteriorFaces(const FiniteElementSpace& fes,
                                                Vector &ea_data_int,
                                                Vector &ea_data_ext)
{
   SetupEA(fes, ea_data_int, ea_data_ext, FaceType::Interior);
}

void DGTraceIntegrator::AssembleEABoundaryFaces(const FiniteElementSpace& fes,
                                                Vector &ea_data_bdr)
{
   //TODO this is wrong
   SetupEA(fes, ea_data_bdr, ea_data_bdr, FaceType::Boundary);
}

}
<commit_msg>Integrate change for boundary vs interior faces.<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#include "../general/forall.hpp"
#include "bilininteg.hpp"
#include "gridfunc.hpp"
#include "../linalg/elementmatrix.hpp"

namespace mfem
{

static void EADGTraceAssemble1D(const int NF,
                                const Array<double> &basis,
                                const Vector &padata,
                                Vector &eadata_int,
                                Vector &eadata_ext,
                                FaceType type)
{
   const bool bdr = type==FaceType::Boundary;
   auto D = Reshape(padata.Read(), 2, 2, NF);
   auto A_int = Reshape(eadata_int.Write(), 2, NF);
   auto A_ext = Reshape(eadata_ext.Write(), 2, NF);
   MFEM_FORALL(f, NF,
   {
      double val_int0, val_int1, val_ext01, val_ext10;
      val_int0  = D(0, 0, f);
      if (bdr)
      {
         val_ext01 = D(1, 0, f);
         val_ext10 = D(0, 1, f);
      }
      val_int1  = D(1, 1, f);
         A_int(0, f) = val_int0;
         A_int(1, f) = val_int1;
      if (bdr)
      {
         A_ext(0, f) = val_ext01;
         A_ext(1, f) = val_ext10;
      }
   });
}

template<int T_D1D = 0, int T_Q1D = 0>
static void EADGTraceAssemble2D(const int NF,
                                const Array<double> &basis,
                                const Vector &padata,
                                Vector &eadata_int,
                                Vector &eadata_ext,
                                FaceType type,
                                const int d1d = 0,
                                const int q1d = 0)
{
   const bool bdr = type==FaceType::Boundary;
   const int D1D = T_D1D ? T_D1D : d1d;
   const int Q1D = T_Q1D ? T_Q1D : q1d;
   MFEM_VERIFY(D1D <= MAX_D1D, "");
   MFEM_VERIFY(Q1D <= MAX_Q1D, "");
   auto B = Reshape(basis.Read(), Q1D, D1D);
   auto D = Reshape(padata.Read(), Q1D, 2, 2, NF);
   auto A_int = Reshape(eadata_int.Write(), D1D, D1D, 2, NF);
   auto A_ext = Reshape(eadata_ext.Write(), D1D, D1D, 2, NF);
   MFEM_FORALL_3D(f, NF, D1D, D1D, 1,
   {
      const int D1D = T_D1D ? T_D1D : d1d;
      const int Q1D = T_Q1D ? T_Q1D : q1d;
      constexpr int MQ1 = T_Q1D ? T_Q1D : MAX_Q1D;
      double r_Bi[MQ1];
      double r_Bj[MQ1];
      for (int q = 0; q < Q1D; q++)
      {
         r_Bi[q] = B(q,MFEM_THREAD_ID(x));
         r_Bj[q] = B(q,MFEM_THREAD_ID(y));
      }
      MFEM_FOREACH_THREAD(i1,x,D1D)
      {
         MFEM_FOREACH_THREAD(j1,y,D1D)
         {
            double val_int0 = 0.0;
            double val_int1 = 0.0;
            double val_ext01 = 0.0;
            double val_ext10 = 0.0;
            for (int k1 = 0; k1 < Q1D; ++k1)
            {
               val_int0  += r_Bi[k1] * r_Bj[k1] * D(k1, 0, 0, f);
               if (bdr)
               {
                  val_ext01 += r_Bi[k1] * r_Bj[k1] * D(k1, 1, 0, f);
                  val_ext10 += r_Bi[k1] * r_Bj[k1] * D(k1, 0, 1, f);
               }
               val_int1  += r_Bi[k1] * r_Bj[k1] * D(k1, 1, 1, f);
            }
            A_int(i1, j1, 0, f) = val_int0;
            A_int(i1, j1, 1, f) = val_int1;
            if (bdr)
            {
               A_ext(i1, j1, 0, f) = val_ext01;
               A_ext(i1, j1, 1, f) = val_ext10;
            }
         }
      }
   });
}

template<int T_D1D = 0, int T_Q1D = 0>
static void EADGTraceAssemble3D(const int NF,
                                const Array<double> &basis,
                                const Vector &padata,
                                Vector &eadata_int,
                                Vector &eadata_ext,
                                FaceType type,
                                const int d1d = 0,
                                const int q1d = 0)
{
   const bool bdr = type==FaceType::Boundary;
   const int D1D = T_D1D ? T_D1D : d1d;
   const int Q1D = T_Q1D ? T_Q1D : q1d;
   MFEM_VERIFY(D1D <= MAX_D1D, "");
   MFEM_VERIFY(Q1D <= MAX_Q1D, "");
   auto B = Reshape(basis.Read(), Q1D, D1D);
   auto D = Reshape(padata.Read(), Q1D, Q1D, 2, 2, NF);
   auto A_int = Reshape(eadata_int.Write(), D1D, D1D, D1D, D1D, 2, NF);
   auto A_ext = Reshape(eadata_ext.Write(), D1D, D1D, D1D, D1D, 2, NF);
   MFEM_FORALL_3D(f, NF, D1D, D1D, 1,
   {
      const int D1D = T_D1D ? T_D1D : d1d;
      const int Q1D = T_Q1D ? T_Q1D : q1d;
      constexpr int MD1 = T_D1D ? T_D1D : MAX_D1D;
      constexpr int MQ1 = T_Q1D ? T_Q1D : MAX_Q1D;
      double r_B[MQ1][MD1];
      for (int d = 0; d < D1D; d++)
      {
         for (int q = 0; q < Q1D; q++)
         {
            r_B[q][d] = B(q,d);
         }
      }
      MFEM_SHARED double s_D[MQ1][MQ1][2][2];
      for (int i; i < 2; i++)
      {
         for (int j; j < 2; j++)
         {
            MFEM_FOREACH_THREAD(k1,x,Q1D)
            {
               MFEM_FOREACH_THREAD(k2,y,Q1D)
               {
                  s_D[k1][k2][i][j] = D(k1,k2,i,j,f);
               }
            }
         }
      }
      MFEM_SYNC_THREAD;
      MFEM_FOREACH_THREAD(i1,x,D1D)
      {
         MFEM_FOREACH_THREAD(i2,y,D1D)
         {
            for (int j1 = 0; j1 < D1D; ++j1)
            {
               for (int j2 = 0; j2 < D1D; ++j2)
               {
                  double val_int0 = 0.0;
                  double val_int1 = 0.0;
                  double val_ext01 = 0.0;
                  double val_ext10 = 0.0;
                  for (int k1 = 0; k1 < Q1D; ++k1)
                  {
                     for (int k2 = 0; k2 < Q1D; ++k2)
                     {
                        val_int0 += r_B[k1][i1] * r_B[k1][j1]
                                  * r_B[k2][i2] * r_B[k2][j2]
                                  * s_D[k1][k2][0][0];
                        val_int1 += r_B[k1][i1] * r_B[k1][j1]
                                  * r_B[k2][i2] * r_B[k2][j2]
                                  * s_D[k1][k2][1][1];
                        if (bdr)
                        {
                           val_ext01+= r_B[k1][i1] * r_B[k1][j1]
                                    * r_B[k2][i2] * r_B[k2][j2]
                                    * s_D[k1][k2][1][0];
                           val_ext10+= r_B[k1][i1] * r_B[k1][j1]
                                    * r_B[k2][i2] * r_B[k2][j2]
                                    * s_D[k1][k2][0][1];
                        }
                     }
                  }
                  A_int(i1, i2, j1, j2, 0, f) = val_int0;
                  A_int(i1, i2, j1, j2, 1, f) = val_int1;
                  if (bdr)
                  {
                     A_ext(i1, i2, j1, j2, 0, f) = val_ext01;
                     A_ext(i1, i2, j1, j2, 1, f) = val_ext10;
                  }
               }
            }
         }
      }
   });
}

void DGTraceIntegrator::SetupEA(const FiniteElementSpace &fes,
                                Vector &ea_data_int,
                                Vector &ea_data_ext,
                                FaceType type)
{
   SetupPA(fes, type);
   nf = fes.GetNFbyType(type);
   const Array<double> &B = maps->B;
   if (dim == 1)
   {
      return EADGTraceAssemble1D(nf,B,pa_data,ea_data_int,ea_data_ext,type);
   }
   else if (dim == 2)
   {
      switch ((dofs1D << 4 ) | quad1D)
      {
         case 0x22: return EADGTraceAssemble2D<2,2>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
         case 0x33: return EADGTraceAssemble2D<3,3>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
         case 0x44: return EADGTraceAssemble2D<4,4>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
         case 0x55: return EADGTraceAssemble2D<5,5>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
         case 0x66: return EADGTraceAssemble2D<6,6>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
         case 0x77: return EADGTraceAssemble2D<7,7>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
         case 0x88: return EADGTraceAssemble2D<8,8>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
         case 0x99: return EADGTraceAssemble2D<9,9>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
         default:   return EADGTraceAssemble2D(nf,B,pa_data,ea_data_int,ea_data_ext,type,dofs1D,quad1D);
      }
   }
   else if (dim == 3)
   {
      switch ((dofs1D << 4 ) | quad1D)
      {
         case 0x23: return EADGTraceAssemble3D<2,3>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
         case 0x34: return EADGTraceAssemble3D<3,4>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
         case 0x45: return EADGTraceAssemble3D<4,5>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
         case 0x56: return EADGTraceAssemble3D<5,6>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
         case 0x67: return EADGTraceAssemble3D<6,7>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
         case 0x78: return EADGTraceAssemble3D<7,8>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
         case 0x89: return EADGTraceAssemble3D<8,9>(nf,B,pa_data,ea_data_int,ea_data_ext,type);
         default:   return EADGTraceAssemble3D(nf,B,pa_data,ea_data_int,ea_data_ext,type,dofs1D,quad1D);
      }
   }
   MFEM_ABORT("Unknown kernel.");
}

void DGTraceIntegrator::AssembleEAInteriorFaces(const FiniteElementSpace& fes,
                                                Vector &ea_data_int,
                                                Vector &ea_data_ext)
{
   SetupEA(fes, ea_data_int, ea_data_ext, FaceType::Interior);
}

void DGTraceIntegrator::AssembleEABoundaryFaces(const FiniteElementSpace& fes,
                                                Vector &ea_data_bdr)
{
   SetupEA(fes, ea_data_bdr, ea_data_bdr, FaceType::Boundary);
}

}
<|endoftext|>