<commit_before>//===--- SerializationTest.cpp - Experimental Object Serialization --------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Ted Kremenek and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file implements prototype code for serialization of objects in clang.
//  It is not intended yet for public use, but simply is a placeholder to
//  experiment with new serialization features.  Serialization will eventually
//  be integrated as a proper component of the clang libraries.
//
//===----------------------------------------------------------------------===//

#include "ASTConsumers.h"
#include "clang/AST/AST.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "llvm/System/Path.h"
#include "llvm/Support/Streams.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Bitcode/Serialize.h"
#include "llvm/Bitcode/Deserialize.h"
#include <stdio.h>
#include <list>

//===----------------------------------------------------------------------===//
// Driver code.
//===----------------------------------------------------------------------===//

using namespace clang;
using llvm::sys::TimeValue;

namespace {

template<typename T> struct Janitor {
  T* Obj;
  Janitor(T* obj) : Obj(obj) {}
  ~Janitor() { delete Obj; }
};

class SerializationTest : public ASTConsumer {
  ASTContext* Context;
  std::list<Decl*> Decls;

  enum { BasicMetadataBlock,
         ASTContextBlock,
         DeclsBlock };

public:
  SerializationTest() : Context(NULL) {};
  ~SerializationTest();

  virtual void Initialize(ASTContext& context, unsigned) {
      Context = &context;
  }

  virtual void HandleTopLevelDecl(Decl *D) {
    Decls.push_back(D);
  }

private:
  void Serialize(llvm::sys::Path& Filename);
  void Deserialize(llvm::sys::Path& Filename);
};

} // end anonymous namespace

ASTConsumer* clang::CreateSerializationTest() {
  return new SerializationTest();
}

static void WritePreamble(llvm::BitstreamWriter& Stream) {
  Stream.Emit((unsigned)'B', 8);
  Stream.Emit((unsigned)'C', 8);
  Stream.Emit(0xC, 4);
  Stream.Emit(0xF, 4);
  Stream.Emit(0xE, 4);
  Stream.Emit(0x0, 4);
}

static bool ReadPreamble(llvm::BitstreamReader& Stream) {
  return Stream.Read(8) != 'B' ||
         Stream.Read(8) != 'C' ||
         Stream.Read(4) != 0xC ||
         Stream.Read(4) != 0xF ||
         Stream.Read(4) != 0xE ||
         Stream.Read(4) != 0x0;
}

void SerializationTest::Serialize(llvm::sys::Path& Filename) {

  // Reserve 256K for bitstream buffer.
  std::vector<unsigned char> Buffer;
  Buffer.reserve(256*1024);

  // Create bitstream and write preamble.
  llvm::BitstreamWriter Stream(Buffer);
  WritePreamble(Stream);

  // Create serializer.
  llvm::Serializer Sezr(Stream);

  // ===---------------------------------------------------===/
  //      Serialize the top-level decls.
  // ===---------------------------------------------------===/

  Sezr.EnterBlock(DeclsBlock);

  // Create a printer to "consume" our deserialized ASTS.
  ASTConsumer* Printer = CreateASTPrinter();
  Janitor<ASTConsumer> PrinterJanitor(Printer);

  for (std::list<Decl*>::iterator I=Decls.begin(), E=Decls.end(); I!=E; ++I) {
    llvm::cerr << "Serializing: Decl.\n";

    Printer->HandleTopLevelDecl(*I);

    Sezr.EmitOwnedPtr(*I);
  }

  Sezr.ExitBlock();

  // ===---------------------------------------------------===/
  //      Serialize the "Translation Unit" metadata.
  // ===---------------------------------------------------===/

  // Emit ASTContext.
  Sezr.EnterBlock(ASTContextBlock);
  llvm::cerr << "Serializing: ASTContext.\n";
  Sezr.EmitOwnedPtr(Context);
  Sezr.ExitBlock();

  Sezr.EnterBlock(BasicMetadataBlock);

  // "Fake" emit the SourceManager.
  llvm::cerr << "Faux-serializing: SourceManager.\n";
  Sezr.EmitPtr(&Context->SourceMgr);

  // "Fake" emit the Target.
  llvm::cerr << "Faux-serializing: Target.\n";
  Sezr.EmitPtr(&Context->Target);

  // "Fake" emit Selectors.
  llvm::cerr << "Faux-serializing: Selectors.\n";
  Sezr.EmitPtr(&Context->Selectors);

  // Emit the Identifier Table.
  llvm::cerr << "Serializing: IdentifierTable.\n";
  Sezr.EmitOwnedPtr(&Context->Idents);

  Sezr.ExitBlock();

  // ===---------------------------------------------------===/
  //      Finalize serialization: write the bits to disk.
  // ===---------------------------------------------------===/

  if (FILE *fp = fopen(Filename.c_str(),"wb")) {
    fwrite((char*)&Buffer.front(), sizeof(char), Buffer.size(), fp);
    fclose(fp);
  }
  else {
    llvm::cerr << "Error: Cannot open " << Filename.c_str() << "\n";
    return;
  }

  llvm::cerr << "Commited bitstream to disk: " << Filename.c_str() << "\n";
}

void SerializationTest::Deserialize(llvm::sys::Path& Filename) {

  // Create the memory buffer that contains the contents of the file.

  using llvm::MemoryBuffer;

  MemoryBuffer* MBuffer = MemoryBuffer::getFile(Filename.c_str(),
                                                strlen(Filename.c_str()));

  if(!MBuffer) {
    llvm::cerr << "ERROR: Cannot read file for deserialization.\n";
    return;
  }

  // Create an "autocollector" object to release the memory buffer upon
  // termination of the current scope.
  Janitor<MemoryBuffer> AutoReleaseBuffer(MBuffer);

  // Check if the file is of the proper length.
  if (MBuffer->getBufferSize() & 0x3) {
    llvm::cerr << "ERROR: AST file length should be a multiple of 4 bytes.\n";
    return;
  }

  // Create the bitstream reader.
  unsigned char *BufPtr = (unsigned char *) MBuffer->getBufferStart();
  llvm::BitstreamReader Stream(BufPtr,BufPtr+MBuffer->getBufferSize());

  // Sniff for the signature in the bitcode file.
  if (ReadPreamble(Stream)) {
    llvm::cerr << "ERROR: Invalid AST-bitcode signature.\n";
    return;
  }

  // Create the deserializer.
  llvm::Deserializer Dezr(Stream);

  // ===---------------------------------------------------===/
  //      Deserialize the "Translation Unit" metadata.
  // ===---------------------------------------------------===/

  // Skip to the BasicMetaDataBlock.  First jump to ASTContextBlock
  // (which will appear earlier) and record its location.

  bool FoundBlock = Dezr.SkipToBlock(ASTContextBlock);
  assert (FoundBlock);

  llvm::Deserializer::Location ASTContextBlockLoc =
    Dezr.getCurrentBlockLocation();

  FoundBlock = Dezr.SkipToBlock(BasicMetadataBlock);
  assert (FoundBlock);

  // "Fake" read the SourceManager.
  llvm::cerr << "Faux-Deserializing: SourceManager.\n";
  Dezr.RegisterPtr(&Context->SourceMgr);

  // "Fake" read the TargetInfo.
  llvm::cerr << "Faux-Deserializing: Target.\n";
  Dezr.RegisterPtr(&Context->Target);

  // "Fake" read the Selectors.
  llvm::cerr << "Faux-Deserializing: Selectors.\n";
  Dezr.RegisterPtr(&Context->Selectors);

  // Read the identifier table.
  llvm::cerr << "Deserializing: IdentifierTable\n";
  Dezr.ReadOwnedPtr<IdentifierTable>();

  // Now jump back to ASTContextBlock and read the ASTContext.
  Dezr.JumpTo(ASTContextBlockLoc);

  // Read the ASTContext.
  llvm::cerr << "Deserializing: ASTContext.\n";
  Dezr.ReadOwnedPtr<ASTContext>();

  // Create a printer to "consume" our deserialized ASTS.
  ASTConsumer* Printer = CreateASTPrinter();
  Janitor<ASTConsumer> PrinterJanitor(Printer);

  // "Rewind" the stream.  Find the block with the serialized top-level decls.
  Dezr.Rewind();
  FoundBlock = Dezr.SkipToBlock(DeclsBlock);
  assert (FoundBlock);
  llvm::Deserializer::Location DeclBlockLoc = Dezr.getCurrentBlockLocation();

  // The remaining objects in the file are top-level decls.
  while (!Dezr.FinishedBlock(DeclBlockLoc)) {
    llvm::cerr << "Deserializing: Decl.\n";
    Decl* decl = Dezr.ReadOwnedPtr<Decl>();
    Printer->HandleTopLevelDecl(decl);
  }
}

SerializationTest::~SerializationTest() {

  std::string ErrMsg;
  llvm::sys::Path Filename = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);

  if (Filename.isEmpty()) {
    llvm::cerr << "Error: " << ErrMsg << "\n";
    return;
  }

  Filename.appendComponent("test.ast");

  if (Filename.makeUnique(true,&ErrMsg)) {
    llvm::cerr << "Error: " << ErrMsg << "\n";
    return;
  }

  Serialize(Filename);
  Deserialize(Filename);
}
<commit_msg>Modified --test-pickling to perform an actual cross-check of serialized ASTs:<commit_after>//===--- SerializationTest.cpp - Experimental Object Serialization --------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Ted Kremenek and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file implements prototype code for serialization of objects in clang.
//  It is not intended yet for public use, but simply is a placeholder to
//  experiment with new serialization features.  Serialization will eventually
//  be integrated as a proper component of the clang libraries.
//
//===----------------------------------------------------------------------===//

#include "ASTConsumers.h"
#include "clang/AST/AST.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "llvm/System/Path.h"
#include "llvm/Support/Streams.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Bitcode/Serialize.h"
#include "llvm/Bitcode/Deserialize.h"
#include <stdio.h>
#include <list>

using namespace clang;
using llvm::sys::TimeValue;

//===----------------------------------------------------------------------===//
// Utility classes
//===----------------------------------------------------------------------===//

namespace {

template<typename T> class Janitor {
  T* Obj;
public:
  explicit Janitor(T* obj) : Obj(obj) {}
  ~Janitor() { delete Obj; }
  operator T*() const { return Obj; }
  T* operator->() { return Obj; }
};

class FileSP {
  FILE* f;
public:
  FileSP(const llvm::sys::Path& fname, const char* mode = "wb")
    : f(fopen(fname.c_str(),mode)) {}

  ~FileSP() { if (f) fclose(f); }

  operator FILE*() const { return f; }
private:
  void operator=(const FileSP& RHS) {}
  FileSP(const FileSP& RHS) {}
};

//===----------------------------------------------------------------------===//
// Driver code.
//===----------------------------------------------------------------------===//

class SerializationTest : public ASTConsumer {
  ASTContext* Context;
  std::list<Decl*> Decls;

  enum { BasicMetadataBlock,
         ASTContextBlock,
         DeclsBlock };

public:
  SerializationTest() : Context(NULL) {};
  ~SerializationTest();

  virtual void Initialize(ASTContext& context, unsigned) {
      Context = &context;
  }

  virtual void HandleTopLevelDecl(Decl *D) {
    Decls.push_back(D);
  }

private:
  void Serialize(llvm::sys::Path& Filename, llvm::sys::Path& FNameDeclPrint);
  void Deserialize(llvm::sys::Path& Filename, llvm::sys::Path& FNameDeclPrint);
};

} // end anonymous namespace

ASTConsumer* clang::CreateSerializationTest() {
  return new SerializationTest();
}

static void WritePreamble(llvm::BitstreamWriter& Stream) {
  Stream.Emit((unsigned)'B', 8);
  Stream.Emit((unsigned)'C', 8);
  Stream.Emit(0xC, 4);
  Stream.Emit(0xF, 4);
  Stream.Emit(0xE, 4);
  Stream.Emit(0x0, 4);
}

static bool ReadPreamble(llvm::BitstreamReader& Stream) {
  return Stream.Read(8) != 'B' ||
         Stream.Read(8) != 'C' ||
         Stream.Read(4) != 0xC ||
         Stream.Read(4) != 0xF ||
         Stream.Read(4) != 0xE ||
         Stream.Read(4) != 0x0;
}

void SerializationTest::Serialize(llvm::sys::Path& Filename,
                                  llvm::sys::Path& FNameDeclPrint) {

  // Reserve 256K for bitstream buffer.
  std::vector<unsigned char> Buffer;
  Buffer.reserve(256*1024);

  // Create bitstream and write preamble.
  llvm::BitstreamWriter Stream(Buffer);
  WritePreamble(Stream);

  // Create serializer.
  llvm::Serializer Sezr(Stream);

  // ===---------------------------------------------------===/
  //      Serialize the top-level decls.
  // ===---------------------------------------------------===/

  Sezr.EnterBlock(DeclsBlock);

  { // Create a printer to "consume" our deserialized ASTS.

    Janitor<ASTConsumer> Printer(CreateASTPrinter());
    FileSP DeclFP(FNameDeclPrint,"w");
    assert (DeclFP && "Could not open file for printing out decls.");
    Janitor<ASTConsumer> FilePrinter(CreateASTPrinter(DeclFP));

    for (std::list<Decl*>::iterator I=Decls.begin(), E=Decls.end(); I!=E; ++I) {
      llvm::cerr << "Serializing: Decl.\n";

      Printer->HandleTopLevelDecl(*I);
      FilePrinter->HandleTopLevelDecl(*I);

      Sezr.EmitOwnedPtr(*I);
    }
  }

  Sezr.ExitBlock();

  // ===---------------------------------------------------===/
  //      Serialize the "Translation Unit" metadata.
  // ===---------------------------------------------------===/

  // Emit ASTContext.
  Sezr.EnterBlock(ASTContextBlock);
  llvm::cerr << "Serializing: ASTContext.\n";
  Sezr.EmitOwnedPtr(Context);
  Sezr.ExitBlock();

  Sezr.EnterBlock(BasicMetadataBlock);

  // "Fake" emit the SourceManager.
  llvm::cerr << "Faux-serializing: SourceManager.\n";
  Sezr.EmitPtr(&Context->SourceMgr);

  // "Fake" emit the Target.
  llvm::cerr << "Faux-serializing: Target.\n";
  Sezr.EmitPtr(&Context->Target);

  // "Fake" emit Selectors.
  llvm::cerr << "Faux-serializing: Selectors.\n";
  Sezr.EmitPtr(&Context->Selectors);

  // Emit the Identifier Table.
  llvm::cerr << "Serializing: IdentifierTable.\n";
  Sezr.EmitOwnedPtr(&Context->Idents);

  Sezr.ExitBlock();

  // ===---------------------------------------------------===/
  // Finalize serialization: write the bits to disk.
  {
    FileSP fp(Filename);

    if (fp)
      fwrite((char*)&Buffer.front(), sizeof(char), Buffer.size(), fp);
    else {
      llvm::cerr << "Error: Cannot open " << Filename.c_str() << "\n";
      return;
    }
  }

  llvm::cerr << "Commited bitstream to disk: " << Filename.c_str() << "\n";
}

void SerializationTest::Deserialize(llvm::sys::Path& Filename,
                                    llvm::sys::Path& FNameDeclPrint) {

  // Create the memory buffer that contains the contents of the file.

  using llvm::MemoryBuffer;

  Janitor<MemoryBuffer> MBuffer(MemoryBuffer::getFile(Filename.c_str(),
                                              strlen(Filename.c_str())));

  if(!MBuffer) {
    llvm::cerr << "ERROR: Cannot read file for deserialization.\n";
    return;
  }

  // Check if the file is of the proper length.
  if (MBuffer->getBufferSize() & 0x3) {
    llvm::cerr << "ERROR: AST file length should be a multiple of 4 bytes.\n";
    return;
  }

  // Create the bitstream reader.
  unsigned char *BufPtr = (unsigned char *) MBuffer->getBufferStart();
  llvm::BitstreamReader Stream(BufPtr,BufPtr+MBuffer->getBufferSize());

  // Sniff for the signature in the bitcode file.
  if (ReadPreamble(Stream)) {
    llvm::cerr << "ERROR: Invalid AST-bitcode signature.\n";
    return;
  }

  // Create the deserializer.
  llvm::Deserializer Dezr(Stream);

  // ===---------------------------------------------------===/
  //      Deserialize the "Translation Unit" metadata.
  // ===---------------------------------------------------===/

  // Skip to the BasicMetaDataBlock.  First jump to ASTContextBlock
  // (which will appear earlier) and record its location.

  bool FoundBlock = Dezr.SkipToBlock(ASTContextBlock);
  assert (FoundBlock);

  llvm::Deserializer::Location ASTContextBlockLoc =
    Dezr.getCurrentBlockLocation();

  FoundBlock = Dezr.SkipToBlock(BasicMetadataBlock);
  assert (FoundBlock);

  // "Fake" read the SourceManager.
  llvm::cerr << "Faux-Deserializing: SourceManager.\n";
  Dezr.RegisterPtr(&Context->SourceMgr);

  // "Fake" read the TargetInfo.
  llvm::cerr << "Faux-Deserializing: Target.\n";
  Dezr.RegisterPtr(&Context->Target);

  // "Fake" read the Selectors.
  llvm::cerr << "Faux-Deserializing: Selectors.\n";
  Dezr.RegisterPtr(&Context->Selectors);

  // Read the identifier table.
  llvm::cerr << "Deserializing: IdentifierTable\n";
  Dezr.ReadOwnedPtr<IdentifierTable>();

  // Now jump back to ASTContextBlock and read the ASTContext.
  Dezr.JumpTo(ASTContextBlockLoc);

  // Read the ASTContext.
  llvm::cerr << "Deserializing: ASTContext.\n";
  Dezr.ReadOwnedPtr<ASTContext>();

  // "Rewind" the stream.  Find the block with the serialized top-level decls.
  Dezr.Rewind();
  FoundBlock = Dezr.SkipToBlock(DeclsBlock);
  assert (FoundBlock);
  llvm::Deserializer::Location DeclBlockLoc = Dezr.getCurrentBlockLocation();

  // Create a printer to "consume" our deserialized ASTS.
  ASTConsumer* Printer = CreateASTPrinter();
  Janitor<ASTConsumer> PrinterJanitor(Printer);
  FileSP DeclFP(FNameDeclPrint,"w");
  assert (DeclFP && "Could not open file for printing out decls.");
  Janitor<ASTConsumer> FilePrinter(CreateASTPrinter(DeclFP));

  // The remaining objects in the file are top-level decls.
  while (!Dezr.FinishedBlock(DeclBlockLoc)) {
    llvm::cerr << "Deserializing: Decl.\n";
    Decl* decl = Dezr.ReadOwnedPtr<Decl>();
    Printer->HandleTopLevelDecl(decl);
    FilePrinter->HandleTopLevelDecl(decl);
  }
}

namespace {
  class TmpDirJanitor {
    llvm::sys::Path& Dir;
  public:
    explicit TmpDirJanitor(llvm::sys::Path& dir) : Dir(dir) {}

    ~TmpDirJanitor() {
      llvm::cerr << "Removing: " << Dir.c_str() << '\n';
      Dir.eraseFromDisk(true);
    }
  };
}

SerializationTest::~SerializationTest() {

  std::string ErrMsg;
  llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);

  if (Dir.isEmpty()) {
    llvm::cerr << "Error: " << ErrMsg << "\n";
    return;
  }

  TmpDirJanitor RemoveTmpOnExit(Dir);

  llvm::sys::Path FNameDeclBefore = Dir;
  FNameDeclBefore.appendComponent("test.decl_before.txt");

  if (FNameDeclBefore.makeUnique(true,&ErrMsg)) {
    llvm::cerr << "Error: " << ErrMsg << "\n";
    return;
  }

  llvm::sys::Path FNameDeclAfter = Dir;
  FNameDeclAfter.appendComponent("test.decl_after.txt");

  if (FNameDeclAfter.makeUnique(true,&ErrMsg)) {
    llvm::cerr << "Error: " << ErrMsg << "\n";
    return;
  }

  llvm::sys::Path ASTFilename = Dir;
  ASTFilename.appendComponent("test.ast");

  if (ASTFilename.makeUnique(true,&ErrMsg)) {
    llvm::cerr << "Error: " << ErrMsg << "\n";
    return;
  }

  // Serialize and then deserialize the ASTs.
  Serialize(ASTFilename, FNameDeclBefore);
  Deserialize(ASTFilename, FNameDeclAfter);

  // Read both pretty-printed files and compare them.

  using llvm::MemoryBuffer;

  Janitor<MemoryBuffer>
    MBufferSer(MemoryBuffer::getFile(FNameDeclBefore.c_str(),
                                     strlen(FNameDeclBefore.c_str())));

  if(!MBufferSer) {
    llvm::cerr << "ERROR: Cannot read pretty-printed file (pre-pickle).\n";
    return;
  }

  Janitor<MemoryBuffer>
    MBufferDSer(MemoryBuffer::getFile(FNameDeclAfter.c_str(),
                                      strlen(FNameDeclAfter.c_str())));

  if(!MBufferDSer) {
    llvm::cerr << "ERROR: Cannot read pretty-printed file (post-pickle).\n";
    return;
  }

  const char *p1 = MBufferSer->getBufferStart();
  const char *e1 = MBufferSer->getBufferEnd();
  const char *p2 = MBufferDSer->getBufferStart();
  const char *e2 = MBufferDSer->getBufferEnd();

  if (MBufferSer->getBufferSize() == MBufferDSer->getBufferSize())
    for ( ; p1 != e1 ; ++p1, ++p2  )
      if (*p1 != *p2) break;

  if (p1 != e1 || p2 != e2 )
    llvm::cerr << "ERROR: Pretty-printed files are not the same.\n";
  else
    llvm::cerr << "SUCCESS: Pretty-printed files are the same.\n";
}
<|endoftext|>


<commit_before>// -----------------------------------------------------------------------------
// Copyright  : (C) 2014 Andreas-C. Bernstein
// License    : MIT (see the file LICENSE)
// Maintainer : Andreas-C. Bernstein <andreas.bernstein@uni-weimar.de>
// Stability  : experimental
//
// Renderer
// -----------------------------------------------------------------------------

#include "renderer.hpp"

Renderer::Renderer() :
_scene{},
_colorbuffer{},
_ppm{}
{}

void Renderer::render()
{

	reserveColorbuffer(_scene._resolution);

	_ppm.setResolution(_scene._resolution);

	raycast();

	/*
	//some testing
	Pixel p(std::get<0>(scene._resolution)/2,std::get<1>(scene._resolution)/2);

	p.color = Color(1.0, 1.0, 1.0);
	write(p);
	*/

	_ppm.save("test");
}

void Renderer::setScene(Scene const& scene)
{
	_scene = scene;
}

void Renderer::reserveColorbuffer(std::tuple<int,int> const& resolution)
{
	float size = std::get<0>(resolution) * std::get<1>(resolution);
	_colorbuffer.resize(size, Color(0.0, 0.0, 0.0));
}

void Renderer::raycast()
{

	float distance = _scene._camera.getDistance(std::get<0>(_scene._resolution));

	Color white{1.0,1.0,1.0};
	Color black{0.0,0.0,0.0};

	//float distance{0.0};

	for (std::vector<Color>::iterator i = _colorbuffer.begin(); i != _colorbuffer.end(); ++i)
	{
		int x = (i - _colorbuffer.begin()) % std::get<0>(_scene._resolution);
		int y =	floor((i - _colorbuffer.begin()) / std::get<0>(_scene._resolution));

		*i = trace(_scene._camera.getEyeRay( x, y, distance));
	}

}

Color Renderer::trace(Ray r)
{
	float distance = 0.0;

	float nearestDistance = 0.0;

	std::shared_ptr<Shape> nearestObject;

	for(std::map<std::string, std::shared_ptr<Shape>>::iterator i = _scene._shapes.begin(); i != _scene._shapes.end(); ++i)
	{
		bool hit = i->second->intersect(r, distance);
		OptionalHit tmp{};

		tmp._hit = hit;

		if(hit)
		{
			if(distance < nearestDistance || nearestDistance == 0.0)
			{
				nearestDistance = distance;
				nearestObject = i->second;
				tmp._shape = i->second;
			}
			else
			{
				tmp._shape = nullptr;
				tmp._t = INFINITY;
			}
		}
		return shade(tmp);
	}
}

Color Renderer::shade(OptionalHit hit)
{
	Color backgroundColor{0.0, 0.0, 0.0};

	if(hit._hit)
	{
		return hit._shape->material().ka();
	}
	else
	{
		return backgroundColor;
	}
}

void Renderer::write(Pixel const& p)
{
	// flip pixels, because of opengl glDrawPixels
	size_t position = (std::get<0>(_resolution)*p.y + p.x);

	if (position >= _colorbuffer.size() || (int)position < 0)
	{
		std::cerr << "Fatal Error Renderer::write(Pixel p) : "
		<< "pixel out of ppm_ : "
		<< (int)p.x << "," << (int)p.y
		<< std::endl;
	}
	else
	{
		_colorbuffer[position] = p.color;
	}

	//extra for the image-file output
	_ppm.write(p);
}

/*
const std::size_t checkersize = 20;

for (unsigned y = 0; y < height_; ++y)
{
	for (unsigned x = 0; x < width_; ++x)
	{
		Pixel p(x,y);
		if ( ((x/checkersize)%2) != ((y/checkersize)%2))
		{
		p.color = Color(0.0, 1.0, float(x)/height_);
		}
		else
		{
		p.color = Color(1.0, 0.0, float(y)/width_);
		}

		write(p);
	}
}
ppm_.save(filename_);
*/<commit_msg>removed unnessecary code<commit_after>// -----------------------------------------------------------------------------
// Copyright  : (C) 2014 Andreas-C. Bernstein
// License    : MIT (see the file LICENSE)
// Maintainer : Andreas-C. Bernstein <andreas.bernstein@uni-weimar.de>
// Stability  : experimental
//
// Renderer
// -----------------------------------------------------------------------------

#include "renderer.hpp"

Renderer::Renderer() :
_scene{},
_colorbuffer{},
_ppm{}
{}

void Renderer::render()
{

	reserveColorbuffer(_scene._resolution);

	_ppm.setResolution(_scene._resolution);

	raycast();

	/*
	//some testing
	Pixel p(std::get<0>(scene._resolution)/2,std::get<1>(scene._resolution)/2);

	p.color = Color(1.0, 1.0, 1.0);
	write(p);
	*/

	_ppm.save("test");
}

void Renderer::setScene(Scene const& scene)
{
	_scene = scene;
}

void Renderer::reserveColorbuffer(std::tuple<int,int> const& resolution)
{
	float size = std::get<0>(resolution) * std::get<1>(resolution);
	_colorbuffer.resize(size, Color(0.0, 0.0, 0.0));
}

void Renderer::raycast()
{

	float distance = _scene._camera.getDistance(std::get<0>(_scene._resolution));

	Color white{1.0,1.0,1.0};
	Color black{0.0,0.0,0.0};

	//float distance{0.0};

	for (std::vector<Color>::iterator i = _colorbuffer.begin(); i != _colorbuffer.end(); ++i)
	{
		int x = (i - _colorbuffer.begin()) % std::get<0>(_scene._resolution);
		int y =	floor((i - _colorbuffer.begin()) / std::get<0>(_scene._resolution));

		*i = trace(_scene._camera.getEyeRay( x, y, distance));
	}

}

Color Renderer::trace(Ray r)
{
	float distance = 0.0;

	float nearestDistance = 0.0;

	std::shared_ptr<Shape> nearestObject;

	for(std::map<std::string, std::shared_ptr<Shape>>::iterator i = _scene._shapes.begin(); i != _scene._shapes.end(); ++i)
	{
		bool hit = i->second->intersect(r, distance);
		OptionalHit tmp{};

		tmp._hit = hit;

		if(hit)
		{
			if(distance < nearestDistance || nearestDistance == 0.0)
			{
				nearestDistance = distance;
				nearestObject = i->second;
				tmp._shape = i->second;
			}
			else
			{
				tmp._shape = nullptr;
				tmp._t = INFINITY;
			}
		}
		return shade(tmp);
	}
}

Color Renderer::shade(OptionalHit hit)
{
	Color backgroundColor{0.0, 0.0, 0.0};

	if(hit._hit)
	{
		return hit._shape->material().ka();
	}
	else
	{
		return backgroundColor;
	}
}

void Renderer::write(Pixel const& p)
{
	// flip pixels, because of opengl glDrawPixels
	size_t position = (std::get<0>(_resolution)*p.y + p.x);

	if (position >= _colorbuffer.size() || (int)position < 0)
	{
		std::cerr << "Fatal Error Renderer::write(Pixel p) : "
		<< "pixel out of ppm_ : "
		<< (int)p.x << "," << (int)p.y
		<< std::endl;
	}
	else
	{
		_colorbuffer[position] = p.color;
	}

	//extra for the image-file output
	_ppm.write(p);
}<|endoftext|>


<commit_before>#include "HTTPServer.hpp"
#include <czmq.h>
#include <iostream>
#include <sstream>
#include <cstring>
#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <assert.h>
#include "zutil.hpp"

#define controlEndpoint "inproc://http/control"

static size_t getFilesize(const char* filename) {
    struct stat st;
    stat(filename, &st);
    return st.st_size;
}

static bool fileExists(const char* file) {
    struct stat buf;
    return (stat(file, &buf) == 0);
}

/**
 * Represents a readonly static file instance which has been mmapped
 * into vmem and possible pre-cached by the kernel.
 */
class MMappedStaticFile {
public:
    /**
     * mmap a new static file.
     */
    MMappedStaticFile(const char* filename) {
        this->size = getFilesize(filename);
        fd = open(filename, O_RDONLY, 0);
        mem = mmap(nullptr, size, PROT_READ, MAP_PRIVATE | MAP_POPULATE, fd, 0);
        assert(mem != nullptr);
        //File will always be sent sequentially
        madvise(mem, size, MADV_SEQUENTIAL);
    }
    ~MMappedStaticFile() {
        assert(munmap(mem, size) == 0);
        close(fd);
    }
    //The mmapped memory
    void* mem;
    size_t size;
private:
    //The file descriptor that is mmapped
    int fd;
};

using namespace std;

YakHTTPServer::YakHTTPServer(zctx_t* ctxParam, const std::string& endpointParam, const std::string& staticFileRoot) : endpoint(endpointParam), ctx(ctxParam), thread(nullptr), logger(ctx, "HTTP Server"), staticFileRoot(staticFileRoot) {
    controlSocket = zsocket_new_bind(ctx, ZMQ_PAIR, controlEndpoint);
    //Start thread
    thread = new std::thread(std::mem_fun(&YakHTTPServer::workerMain), this);
}

//Static HTTP error msgs
static const char securityErrorMessage[] = "HTTP/1.1 403 Forbidden\r\nContent-type: text/plain\r\n\r\nSecurity error: Path must not contain ..";
static const char notFoundError[] = "HTTP/1.1 404 Not Found\r\nContent-type: text/plain\r\n\r\nFile not found";

/**
 * @return A constant string representing the MIME type, e.g. "text/plain")
 */
static const char* getMIMEType(const char* buffer) {
    //Find the beginning of the file ext === the last '.' occurrence -> strRchr
    const char* fileExtensionPtr = strrchr(buffer, '.');
    if(fileExtensionPtr == nullptr) {
        return "text/plain";
    }

    //We found an extension
    if(strcmp(".html", fileExtensionPtr) == 0) {
        return "text/html";
    } else if(strcmp(".js", fileExtensionPtr) == 0) {
        return "text/javascript";
    } else if(strcmp(".css", fileExtensionPtr) == 0) {
        return "text/css";
    } else if(strcmp(".jpg", fileExtensionPtr) == 0
        || strcmp(".jpeg", fileExtensionPtr) == 0) {
        return "image/jpeg";
    } else if(strcmp(".png", fileExtensionPtr) == 0) {
        return "image/png";
    } else if(strcmp(".ico", fileExtensionPtr) == 0) {
        return "image/x-icon";
    } else {
        return "text/plain";
    }
}

void YakHTTPServer::serveStaticFile(const char* fileURL) {
    sendReplyIdentity();
    //Security: Check if the file contains relative paths
    if(strstr(fileURL, "..") != nullptr) {
        zmq_send_const(httpSocket, securityErrorMessage, sizeof(securityErrorMessage), 0);
        return;
    }
    //No security violation, check if the file exists
    if(fileURL[0] == '/') {
        fileURL++;
    }
    if(fileURL[0] == '\0') {
        fileURL = "index.html";
    }
    string absoluteFilePath = staticFileRoot + string(fileURL);
    if(!fileExists(absoluteFilePath.c_str())) {
        zmq_send_const(httpSocket, notFoundError, sizeof(notFoundError), 0);
        return;
    }
    //File exists, mmap if neccessary
    if(mappedFiles.count(absoluteFilePath) == 0) {
        mappedFiles[absoluteFilePath] = new MMappedStaticFile(absoluteFilePath.c_str());
    }
    MMappedStaticFile* file = mappedFiles[absoluteFilePath];
    const char* mimeType = getMIMEType(fileURL);
    //Send the header
    string header("HTTP/1.1 200 OK\r\nContent-type: " + string(mimeType)
                    + "\r\nContent-Length: " + std::to_string(file->size) +  "\r\n\r\n");
    zmq_send_const(httpSocket, header.data(), header.size(), 0);
    //Send data
    sendReplyIdentity();
    zmq_send_const(httpSocket, file->mem, file->size, 0);
}

void YakHTTPServer::sendReplyIdentity() {
    if(unlikely(zmq_send_const (httpSocket, replyAddr, replyAddrSize, ZMQ_SNDMORE) == -1)) {
        logger.error("Error while sending stream reply adress: " + string(zmq_strerror(errno)));
    }
}

void YakHTTPServer::workerMain() {
    //TODO proper error handling
    logger.trace("HTTP Server starting");
    //Initialize router socket
    httpSocket = zsocket_new(ctx, ZMQ_STREAM);
    assert(zsocket_bind(httpSocket, endpoint.c_str()) != -1);
    //Initialize other stuff
    zmq_msg_t replyAddrFrame;
    zmq_msg_init(&replyAddrFrame);
    zmq_msg_t request;
    zmq_msg_init(&request);
    zmq_msg_t response;
    zmq_msg_init(&response);
    //Initialize control socket (receives STOP cmd etc.)
    void* controlRecvSocket = zsocket_new_connect(ctx, ZMQ_PAIR, controlEndpoint);
    zmq_pollitem_t items[2];
    items[0].socket = httpSocket;
    items[0].events = ZMQ_POLLIN;
    items[1].socket = controlRecvSocket;
    items[1].events = ZMQ_POLLIN;
    while(true) {
         //  Get HTTP request
        assert(zmq_poll(items, 2, -1) != -1);
        //Check if we received a control msg
        if(items[1].revents) {
            //It must be a stop message
            zmq_recv(controlRecvSocket, nullptr, 0, 0);
            break;
        }
        assert(items[0].revents);
        //Receive the reply adress
        zmq_msg_init(&replyAddrFrame);
        if(unlikely(zmq_msg_recv(&replyAddrFrame, httpSocket, 0) == -1)) {
            logger.error("HTTP critical error: Reply address could not be received correctly: " + string(zmq_strerror(errno)));
            continue;
        }
        //Receive the request itself (might be multi-part but we're ATM not interested in all the header
        if(unlikely(zmq_msg_recv(&request, httpSocket, 0) == -1)) {
            logger.error("Error while receiving HTTP request: " + std::string(zmq_strerror(errno)));
            continue;
        }
        //Extract the request type from the request
        char* requestData = (char*)zmq_msg_data(&request);
        bool isGETRequest = (memcmp(requestData, "GET ", 4) == 0);
        assert(isGETRequest);
        //Ensure there are no frames left to receive!
        recvAndIgnore(httpSocket);
        //Make a NUL-delimited string from the request path
        char* requestPath = strchr(requestData, ' ') + 1;
        *(strchr(requestPath, ' ')) = '\0';
        /**
         * NOTE: Even if the reply adress is non-const data,
         * it is deallocated by the IO thread when the connection is closed
         * and certainly won't change, so we can treat it as constant
         * and therefore zero-copy data while the HTTP connection is open
         */
        replyAddr = (char*) zmq_msg_data(&replyAddrFrame);
        replyAddrSize = zmq_msg_size(&replyAddrFrame);
        //TODO Check routes
        serveStaticFile(requestPath);
        //Cleanup
        closeTCPConnection();
        zmq_msg_close(&replyAddrFrame);
    }
    logger.debug("HTTP Server terminating...");
    zsocket_destroy(ctx, controlRecvSocket);
    zsocket_destroy(ctx, httpSocket);
    httpSocket = nullptr;
}

void YakHTTPServer::closeTCPConnection() {
    sendReplyIdentity();
    sendEmptyFrameMessage(httpSocket);
}

void YakHTTPServer::terminate() {
    if(thread != nullptr) {
        //Send control msg
        zmq_send(controlSocket, NULL, 0, 0);
        zsocket_destroy(ctx, controlSocket);
        //Wait until the thread exists
        thread->join();
        delete thread;
        thread = nullptr;
    }
    logger.terminate();
}

YakHTTPServer::~YakHTTPServer() {
    terminate();
    //munmap all mmapped files
    for(auto pair : mappedFiles) {
        delete pair.second;
    }
}<commit_msg>Added log message on mmap<commit_after>#include "HTTPServer.hpp"
#include <czmq.h>
#include <iostream>
#include <sstream>
#include <cstring>
#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <assert.h>
#include "zutil.hpp"

#define controlEndpoint "inproc://http/control"

static size_t getFilesize(const char* filename) {
    struct stat st;
    stat(filename, &st);
    return st.st_size;
}

static bool fileExists(const char* file) {
    struct stat buf;
    return (stat(file, &buf) == 0);
}

/**
 * Represents a readonly static file instance which has been mmapped
 * into vmem and possible pre-cached by the kernel.
 */
class MMappedStaticFile {
public:
    /**
     * mmap a new static file.
     */
    MMappedStaticFile(const char* filename) {
        this->size = getFilesize(filename);
        fd = open(filename, O_RDONLY, 0);
        mem = mmap(nullptr, size, PROT_READ, MAP_PRIVATE | MAP_POPULATE, fd, 0);
        assert(mem != nullptr);
        //File will always be sent sequentially
        madvise(mem, size, MADV_SEQUENTIAL);
    }
    ~MMappedStaticFile() {
        assert(munmap(mem, size) == 0);
        close(fd);
    }
    //The mmapped memory
    void* mem;
    size_t size;
private:
    //The file descriptor that is mmapped
    int fd;
};

using namespace std;

YakHTTPServer::YakHTTPServer(zctx_t* ctxParam, const std::string& endpointParam, const std::string& staticFileRoot) : endpoint(endpointParam), ctx(ctxParam), thread(nullptr), logger(ctx, "HTTP Server"), staticFileRoot(staticFileRoot) {
    controlSocket = zsocket_new_bind(ctx, ZMQ_PAIR, controlEndpoint);
    //Start thread
    thread = new std::thread(std::mem_fun(&YakHTTPServer::workerMain), this);
}

//Static HTTP error msgs
static const char securityErrorMessage[] = "HTTP/1.1 403 Forbidden\r\nContent-type: text/plain\r\n\r\nSecurity error: Path must not contain ..";
static const char notFoundError[] = "HTTP/1.1 404 Not Found\r\nContent-type: text/plain\r\n\r\nFile not found";

/**
 * @return A constant string representing the MIME type, e.g. "text/plain")
 */
static const char* getMIMEType(const char* buffer) {
    //Find the beginning of the file ext === the last '.' occurrence -> strRchr
    const char* fileExtensionPtr = strrchr(buffer, '.');
    if(fileExtensionPtr == nullptr) {
        return "text/plain";
    }

    //We found an extension
    if(strcmp(".html", fileExtensionPtr) == 0) {
        return "text/html";
    } else if(strcmp(".js", fileExtensionPtr) == 0) {
        return "text/javascript";
    } else if(strcmp(".css", fileExtensionPtr) == 0) {
        return "text/css";
    } else if(strcmp(".jpg", fileExtensionPtr) == 0
        || strcmp(".jpeg", fileExtensionPtr) == 0) {
        return "image/jpeg";
    } else if(strcmp(".png", fileExtensionPtr) == 0) {
        return "image/png";
    } else if(strcmp(".ico", fileExtensionPtr) == 0) {
        return "image/x-icon";
    } else {
        return "text/plain";
    }
}

void YakHTTPServer::serveStaticFile(const char* fileURL) {
    sendReplyIdentity();
    //Security: Check if the file contains relative paths
    if(strstr(fileURL, "..") != nullptr) {
        zmq_send_const(httpSocket, securityErrorMessage, sizeof(securityErrorMessage), 0);
        return;
    }
    //No security violation, check if the file exists
    if(fileURL[0] == '/') {
        fileURL++;
    }
    if(fileURL[0] == '\0') {
        fileURL = "index.html";
    }
    string absoluteFilePath = staticFileRoot + string(fileURL);
    if(!fileExists(absoluteFilePath.c_str())) {
        zmq_send_const(httpSocket, notFoundError, sizeof(notFoundError), 0);
        return;
    }
    //File exists, mmap if neccessary
    if(mappedFiles.count(absoluteFilePath) == 0) {
        logger.trace("mmap'ing static file " + absoluteFilePath);
        mappedFiles[absoluteFilePath] = new MMappedStaticFile(absoluteFilePath.c_str());
    }
    MMappedStaticFile* file = mappedFiles[absoluteFilePath];
    const char* mimeType = getMIMEType(fileURL);
    //Send the header
    string header("HTTP/1.1 200 OK\r\nContent-type: " + string(mimeType)
                    + "\r\nContent-Length: " + std::to_string(file->size) +  "\r\n\r\n");
    zmq_send_const(httpSocket, header.data(), header.size(), 0);
    //Send data
    sendReplyIdentity();
    zmq_send_const(httpSocket, file->mem, file->size, 0);
}

void YakHTTPServer::sendReplyIdentity() {
    if(unlikely(zmq_send_const (httpSocket, replyAddr, replyAddrSize, ZMQ_SNDMORE) == -1)) {
        logger.error("Error while sending stream reply adress: " + string(zmq_strerror(errno)));
    }
}

void YakHTTPServer::workerMain() {
    //TODO proper error handling
    logger.trace("HTTP Server starting");
    //Initialize router socket
    httpSocket = zsocket_new(ctx, ZMQ_STREAM);
    assert(zsocket_bind(httpSocket, endpoint.c_str()) != -1);
    //Initialize other stuff
    zmq_msg_t replyAddrFrame;
    zmq_msg_init(&replyAddrFrame);
    zmq_msg_t request;
    zmq_msg_init(&request);
    zmq_msg_t response;
    zmq_msg_init(&response);
    //Initialize control socket (receives STOP cmd etc.)
    void* controlRecvSocket = zsocket_new_connect(ctx, ZMQ_PAIR, controlEndpoint);
    zmq_pollitem_t items[2];
    items[0].socket = httpSocket;
    items[0].events = ZMQ_POLLIN;
    items[1].socket = controlRecvSocket;
    items[1].events = ZMQ_POLLIN;
    while(true) {
         //  Get HTTP request
        assert(zmq_poll(items, 2, -1) != -1);
        //Check if we received a control msg
        if(items[1].revents) {
            //It must be a stop message
            zmq_recv(controlRecvSocket, nullptr, 0, 0);
            break;
        }
        assert(items[0].revents);
        //Receive the reply adress
        zmq_msg_init(&replyAddrFrame);
        if(unlikely(zmq_msg_recv(&replyAddrFrame, httpSocket, 0) == -1)) {
            logger.error("HTTP critical error: Reply address could not be received correctly: " + string(zmq_strerror(errno)));
            continue;
        }
        //Receive the request itself (might be multi-part but we're ATM not interested in all the header
        if(unlikely(zmq_msg_recv(&request, httpSocket, 0) == -1)) {
            logger.error("Error while receiving HTTP request: " + std::string(zmq_strerror(errno)));
            continue;
        }
        //Extract the request type from the request
        char* requestData = (char*)zmq_msg_data(&request);
        bool isGETRequest = (memcmp(requestData, "GET ", 4) == 0);
        assert(isGETRequest);
        //Ensure there are no frames left to receive!
        recvAndIgnore(httpSocket);
        //Make a NUL-delimited string from the request path
        char* requestPath = strchr(requestData, ' ') + 1;
        *(strchr(requestPath, ' ')) = '\0';
        /**
         * NOTE: Even if the reply adress is non-const data,
         * it is deallocated by the IO thread when the connection is closed
         * and certainly won't change, so we can treat it as constant
         * and therefore zero-copy data while the HTTP connection is open
         */
        replyAddr = (char*) zmq_msg_data(&replyAddrFrame);
        replyAddrSize = zmq_msg_size(&replyAddrFrame);
        //TODO Check routes
        serveStaticFile(requestPath);
        //Cleanup
        closeTCPConnection();
        zmq_msg_close(&replyAddrFrame);
    }
    logger.debug("HTTP Server terminating...");
    zsocket_destroy(ctx, controlRecvSocket);
    zsocket_destroy(ctx, httpSocket);
    httpSocket = nullptr;
}

void YakHTTPServer::closeTCPConnection() {
    sendReplyIdentity();
    sendEmptyFrameMessage(httpSocket);
}

void YakHTTPServer::terminate() {
    if(thread != nullptr) {
        //Send control msg
        zmq_send(controlSocket, NULL, 0, 0);
        zsocket_destroy(ctx, controlSocket);
        //Wait until the thread exists
        thread->join();
        delete thread;
        thread = nullptr;
    }
    logger.terminate();
}

YakHTTPServer::~YakHTTPServer() {
    terminate();
    //munmap all mmapped files
    for(auto pair : mappedFiles) {
        delete pair.second;
    }
}<|endoftext|>


<commit_before>#ifndef SIXTRACKLIB_SIXTRACKLIB_HPP__
#define SIXTRACKLIB_SIXTRACKLIB_HPP__

/* ------------------------------------------------------------------------- */

#include "sixtracklib/common/generated/namespace.h"
#include "sixtracklib/common/generated/config.h"
#include "sixtracklib/common/definitions.h"

#include "sixtracklib/common/buffer.hpp"
#include "sixtracklib/common/be_drift/be_drift.hpp"
#include "sixtracklib/common/particles.hpp"

#include "sixtracklib/sixtracklib.h"

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

#if defined( SIXTRACKLIB_ENABLE_MODULE_SIMD ) && \
           ( SIXTRACKLIB_ENABLE_MODULE_SIMD == 1 )

//     #include "sixtracklib/simd/track.h"

#endif /* defined( SIXTRACKLIB_ENABLE_MODULE_SIMD ) */

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

#if defined( SIXTRACKLIB_ENABLE_MODULE_OPENCL ) && \
           ( SIXTRACKLIB_ENABLE_MODULE_OPENCL == 1 )

//     #include "sixtracklib/opencl/argument.h"
//     #include "sixtracklib/opencl/context.h"

//     #include "sixtracklib/opencl/buffer.h"
//     #include "sixtracklib/opencl/ocl_environment.h"

#endif /* defined( SIXTRACKLIB_ENABLE_MODULE_OPENCL ) */

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

#if defined( SIXTRACKLIB_ENABLE_MODULE_CUDA ) && \
           ( SIXTRACKLIB_ENABLE_MODULE_CUDA == 1 )

//     #include "sixtracklib/cuda/buffer.h"
//     #include "sixtracklib/cuda/impl/track_particles_kernel_c_wrapper.h"

#endif /* defined( SIXTRACKLIB_ENABLE_MODULE_OPENCL ) */

/* ------------------------------------------------------------------------- */

#endif /* SIXTRACKLIB_SIXTRACKLIB_HPP__ */

/* end: sixtracklib/sixtracklib.hpp */
<commit_msg>common: adds missing header for st::BeamMonitor to convenience header sixtracklib.hpp<commit_after>#ifndef SIXTRACKLIB_SIXTRACKLIB_HPP__
#define SIXTRACKLIB_SIXTRACKLIB_HPP__

/* ------------------------------------------------------------------------- */

#include "sixtracklib/common/generated/namespace.h"
#include "sixtracklib/common/generated/config.h"
#include "sixtracklib/common/definitions.h"

#include "sixtracklib/common/buffer.hpp"
#include "sixtracklib/common/be_drift/be_drift.hpp"
#include "sixtracklib/common/be_monitor/be_monitor.hpp"
#include "sixtracklib/common/particles.hpp"

#include "sixtracklib/sixtracklib.h"

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

#if defined( SIXTRACKLIB_ENABLE_MODULE_SIMD ) && \
           ( SIXTRACKLIB_ENABLE_MODULE_SIMD == 1 )

//     #include "sixtracklib/simd/track.h"

#endif /* defined( SIXTRACKLIB_ENABLE_MODULE_SIMD ) */

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

#if defined( SIXTRACKLIB_ENABLE_MODULE_OPENCL ) && \
           ( SIXTRACKLIB_ENABLE_MODULE_OPENCL == 1 )

//     #include "sixtracklib/opencl/argument.h"
//     #include "sixtracklib/opencl/context.h"

//     #include "sixtracklib/opencl/buffer.h"
//     #include "sixtracklib/opencl/ocl_environment.h"

#endif /* defined( SIXTRACKLIB_ENABLE_MODULE_OPENCL ) */

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

#if defined( SIXTRACKLIB_ENABLE_MODULE_CUDA ) && \
           ( SIXTRACKLIB_ENABLE_MODULE_CUDA == 1 )

//     #include "sixtracklib/cuda/buffer.h"
//     #include "sixtracklib/cuda/impl/track_particles_kernel_c_wrapper.h"

#endif /* defined( SIXTRACKLIB_ENABLE_MODULE_OPENCL ) */

/* ------------------------------------------------------------------------- */

#endif /* SIXTRACKLIB_SIXTRACKLIB_HPP__ */

/* end: sixtracklib/sixtracklib.hpp */
<|endoftext|>


<commit_before>/*
 *  Phusion Passenger - https://www.phusionpassenger.com/
 *  Copyright (c) 2010 Phusion
 *
 *  "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 */
#include <iomanip>
#include <cstdlib>
#include <fcntl.h>
#include <unistd.h>
#include <Logging.h>

namespace Passenger {

int _logLevel = 0;
int _logOutput = STDERR_FILENO;

int
getLogLevel() {
	return _logLevel;
}

void
setLogLevel(int value) {
	_logLevel = value;
}

bool
setDebugFile(const char *logFile) {
	int fd = open(logFile, O_WRONLY | O_CREAT | O_APPEND, 0644);
	if (fd != -1) {
		_logOutput = fd;
		return true;
	} else {
		return false;
	}
}

void
_prepareLogEntry(std::stringstream &sstream, const char *file, unsigned int line) {
	time_t the_time;
	struct tm the_tm;
	char datetime_buf[60];
	struct timeval tv;

	the_time = time(NULL);
	localtime_r(&the_time, &the_tm);
	strftime(datetime_buf, sizeof(datetime_buf) - 1, "%F %H:%M:%S", &the_tm);
	gettimeofday(&tv, NULL);
	sstream <<
		"[ pid=" << std::dec << getpid() <<
		" thr=" << std::hex << pthread_self() << std::dec <<
		" time=" << datetime_buf << "." << std::setfill('0') << std::setw(4) <<
			(unsigned long) (tv.tv_usec / 100) <<
		" file=" << file << ":" << line <<
		" ]: ";
}

void
_writeLogEntry(const std::string &str) {
	size_t written = 0;
	do {
		ssize_t ret = write(_logOutput, str.data() + written, str.size() - written);
		if (ret != -1) {
			written += ret;
		}
	} while (written < str.size());
}

} // namespace Passenger

<commit_msg>Make log output more compact.<commit_after>/*
 *  Phusion Passenger - https://www.phusionpassenger.com/
 *  Copyright (c) 2010 Phusion
 *
 *  "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 */
#include <iomanip>
#include <cstdlib>
#include <fcntl.h>
#include <unistd.h>
#include <Logging.h>
#include <Utils/StrIntUtils.h>

namespace Passenger {

int _logLevel = 0;
int _logOutput = STDERR_FILENO;

int
getLogLevel() {
	return _logLevel;
}

void
setLogLevel(int value) {
	_logLevel = value;
}

bool
setDebugFile(const char *logFile) {
	int fd = open(logFile, O_WRONLY | O_CREAT | O_APPEND, 0644);
	if (fd != -1) {
		_logOutput = fd;
		return true;
	} else {
		return false;
	}
}

void
_prepareLogEntry(std::stringstream &sstream, const char *file, unsigned int line) {
	time_t the_time;
	struct tm the_tm;
	char datetime_buf[60];
	struct timeval tv;

	if (startsWith(file, "ext/")) {
		file += sizeof("ext/") - 1;
		if (startsWith(file, "common/")) {
			file += sizeof("common/") - 1;
		}
	}

	the_time = time(NULL);
	localtime_r(&the_time, &the_tm);
	strftime(datetime_buf, sizeof(datetime_buf) - 1, "%F %H:%M:%S", &the_tm);
	gettimeofday(&tv, NULL);
	sstream <<
		"[ " << std::dec << getpid() <<
		"/" << std::hex << pthread_self() << std::dec <<
		" " << datetime_buf << "." << std::setfill('0') << std::setw(4) <<
			(unsigned long) (tv.tv_usec / 100) <<
		" " << file << ":" << line <<
		" ]: ";
}

void
_writeLogEntry(const std::string &str) {
	size_t written = 0;
	do {
		ssize_t ret = write(_logOutput, str.data() + written, str.size() - written);
		if (ret != -1) {
			written += ret;
		}
	} while (written < str.size());
}

} // namespace Passenger

<|endoftext|>


<commit_before>/**
 *  @file
 *  @author     2012 Stefan Radomski (stefan.radomski@cs.tu-darmstadt.de)
 *  @copyright  Simplified BSD
 *
 *  @cond
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the FreeBSD license as published by the FreeBSD
 *  project.
 *
 *  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.
 *
 *  You should have received a copy of the FreeBSD license along with this
 *  program. If not, see <http://www.opensource.org/licenses/bsd-license>.
 *  @endcond
 */

#include "umundo/protoc-rpc/ServiceGeneratorCPP.h"

#include <set>
#include <iostream>

#include <google/protobuf/compiler/plugin.h>
#include <google/protobuf/compiler/cpp/cpp_file.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/descriptor.pb.h>

namespace umundo {

using namespace google::protobuf::compiler::cpp;

bool ServiceGeneratorCPP::Generate(const FileDescriptor* file,
                                   const string& parameter,
                                   GeneratorContext* generator_context,
                                   string* error) const {
	vector<pair<string, string> > options;
	ParseGeneratorParameter(parameter, &options);

	string dllexport_decl;
	for (size_t i = 0; i < options.size(); i++) {
		if (options[i].first == "dllexport_decl") {
			dllexport_decl = options[i].second;
		} else {
			*error = "Unknown generator option: " + options[i].first;
			return false;
		}
	}

	string basename = StripProto(file->name());
	string filenameID = FilenameIdentifier(file->name());

	// Generate header.
	{
		scoped_ptr<io::ZeroCopyOutputStream> output(generator_context->Open(basename + ".rpc.pb.h"));
		io::Printer printer(output.get(), '$');

		// header prolog
		printer.Print(
		    "// Generated by the umundo protocol buffer compiler. DO NOT EDIT!\n"
		    "// source: $filename$\n\n"
		    "#ifndef __PROTOBUF_$filename_identifier$\n"
		    "#define __PROTOBUF_$filename_identifier$\n\n"
		    "#include <umundo/rpc.h>\n"
		    "#include \"$basename$.pb.h\" // generated by protoc\n"
		    "#include \"$basename$.rpc.pb.h\" // generated by protoc\n",

		    "basename", basename,
		    "filename", file->name(),
		    "filename_identifier", filenameID);

		if (file->dependency_count() > 0) {
			for (int i = 0; i < file->dependency_count(); i++) {
				const FileDescriptor* fileDesc = file->dependency(i);
				printer.Print("#include \"$dependency$.pb.h\" // generated by protoc\n", "dependency", StripProto(fileDesc->name()));
			}
		}

		printer.Print("\n\nnamespace umundo {\n\n");

		if (file->service_count() > 0) {
			for (int i = 0; i < file->service_count(); i++) {
				const ServiceDescriptor* svcDesc = file->service(i);
				writeServiceStubHeader(printer, svcDesc);
				printer.Print("\n");
				writeServiceHeader(printer, svcDesc);
				printer.Print("\n\n");
			}
		}

		// header epilog
		printer.Print(
		    "\n}\n"
		    "#endif\n");
	}

	// Generate cc file.
	{
		scoped_ptr<io::ZeroCopyOutputStream> output(generator_context->Open(basename + ".rpc.pb.cc"));
		io::Printer printer(output.get(), '$');

		if (file->service_count() > 0) {
			// implementation prolog
			printer.Print(
			    "#include \"umundo/rpc/Service.h\"\n"
			    "#include \"umundo/rpc/ServiceManager.h\"\n"
			    "#include \"$basename$.rpc.pb.h\"\n\n"
			    "namespace umundo {\n\n",
			    "basename", basename
			);

			for (int i = 0; i < file->service_count(); i++) {
				const ServiceDescriptor* svcDesc = file->service(i);
				writeServiceImplConstructor(printer, svcDesc);
				printer.Print("\n");
				writeServiceImplDispatcher(printer, svcDesc);
				printer.Print("\n");
				writeServiceImplCleanUp(printer, svcDesc);
				printer.Print("\n");
				writeServiceStubImpl(printer, svcDesc);
				printer.Print("\n\n");
			}
		}

		if (file->service_count() > 0) {
			// implementation epilog
			printer.Print("\n}\n");
		}
	}

	return true;

}

void ServiceGeneratorCPP::writeServiceStubHeader(io::Printer& printer, const ServiceDescriptor* svcDesc) const {
	printer.Print(
	    "class $svcName$Stub : public ServiceStub {\n"
	    "public:\n"
	    "\t$svcName$Stub(ServiceDescription*);\n",
	    "svcName", svcDesc->name()
	);

	if (svcDesc->method_count() > 0) {
		for (int i = 0; i < svcDesc->method_count(); i++) {
			const MethodDescriptor* methodDesc = svcDesc->method(i);
			printer.Print("\t$outType$* $methodName$($inType$*);\n",
			              "inType", container(methodDesc->input_type())->name(),
			              "methodName", methodDesc->name(),
			              "outType", container(methodDesc->output_type())->name()
			             );
		}
	}
	printer.Print("};\n");
}

void ServiceGeneratorCPP::writeServiceHeader(io::Printer &printer, const ServiceDescriptor* svcDesc) const {
	printer.Print(
	    "class $svcName$Base : public Service {\n"
	    "public:\n"
	    "\t$svcName$Base();\n",
	    "svcName", svcDesc->name()
	);

	if (svcDesc->method_count() > 0) {
		for (int i = 0; i < svcDesc->method_count(); i++) {
			const MethodDescriptor* methodDesc = svcDesc->method(i);
			printer.Print("\tvirtual $outType$* $methodName$($inType$*) = 0;\n",
			              "inType", container(methodDesc->input_type())->name(),
			              "methodName", methodDesc->name(),
			              "outType", container(methodDesc->output_type())->name()
			             );
		}

		printer.Print(
		    "protected:\n"
		    "\tvoid callMethod(string&, void*, const string&, void*&, const string&);\n"
		    "\tvoid cleanUpObjects(string&, void*, void*);\n"
		);
	}
	printer.Print("};\n");
}

const Descriptor* ServiceGeneratorCPP::container(const Descriptor* desc) {
//	fprintf(stderr, "checking %s\n", desc->name().c_str());
	while(desc->containing_type() != NULL) {
		desc = desc->containing_type();
//		fprintf(stderr, "\t-> %s\n", desc->name().c_str());
	}
	return desc;
}

void ServiceGeneratorCPP::writeServiceImplConstructor(io::Printer& printer, const ServiceDescriptor* svcDesc) const {

	std::set<string> inTypes;
	std::set<string> outTypes;
	std::set<string>::iterator inTypeIter;
	std::set<string>::iterator outTypeIter;

	if (svcDesc->method_count() > 0) {
		for (int i = 0; i < svcDesc->method_count(); i++) {
			const MethodDescriptor* methodDesc = svcDesc->method(i);
			inTypes.insert(methodDesc->input_type()->name());
			outTypes.insert(methodDesc->output_type()->name());
		}
	}

	printer.Print(
	    "$className$Stub::$className$Stub(ServiceDescription* svcDesc) : ServiceStub(svcDesc)  {\n"
	    "\t_serviceName = \"$className$\";\n",
	    "className", svcDesc->name()
	);

	// register intypes at publisher for stub, outtypes at subscriber
	for (inTypeIter = inTypes.begin(); inTypeIter != inTypes.end(); inTypeIter++) {
		printer.Print(
		    "\t_rpcPub->registerType(\"$inType$\", new $inType$());\n",
		    "inType", (*inTypeIter)
		);
	}
	for (outTypeIter = outTypes.begin(); outTypeIter != outTypes.end(); outTypeIter++) {
		printer.Print(
		    "\t_rpcSub->registerType(\"$outType$\", new $outType$());\n",
		    "outType", (*outTypeIter)
		);
	}

	printer.Print("}\n\n");

	printer.Print(
	    "$className$Base::$className$Base() {\n"
	    "\t_serviceName = \"$className$\";\n",
	    "className", svcDesc->name()
	);

	// register intypes at sublisher for impl, outtypes at publisher
	for (inTypeIter = inTypes.begin(); inTypeIter != inTypes.end(); inTypeIter++) {
		printer.Print(
		    "\t_rpcSub->registerType(\"$inType$\", new $inType$());\n",
		    "inType", (*inTypeIter)
		);
	}
	for (outTypeIter = outTypes.begin(); outTypeIter != outTypes.end(); outTypeIter++) {
		printer.Print(
		    "\t_rpcPub->registerType(\"$outType$\", new $outType$());\n",
		    "outType", (*outTypeIter)
		);
	}

	printer.Print("}\n");

}

void ServiceGeneratorCPP::writeServiceImplDispatcher(io::Printer& printer, const ServiceDescriptor* svcDesc) const {

	printer.Print(
	    "void $className$Base::callMethod(string& methodName, void* in, const string& inType, void* &out, const string& outType) {\n"
	    "\tif (false) {\n",
	    "className", svcDesc->name()
	);

	if (svcDesc->method_count() > 0) {
		for (int i = 0; i < svcDesc->method_count(); i++) {
			const MethodDescriptor* methodDesc = svcDesc->method(i);
			printer.Print(
			    "\t} else if (methodName.compare(\"$methodName$\") == 0) {\n"
			    "\t\tout = (void*)$methodName$(($inType$*)in);\n",
			    "inType", methodDesc->input_type()->name(),
			    "methodName", methodDesc->name()
			);
		}
	}
	printer.Print("\t}\n}\n");
}

void ServiceGeneratorCPP::writeServiceImplCleanUp(io::Printer& printer, const ServiceDescriptor* svcDesc) const {
	printer.Print(
	    "void $className$Base::cleanUpObjects(string& methodName, void* in, void* out) {\n"
	    "\tif (false) {\n",
	    "className", svcDesc->name()
	);

	if (svcDesc->method_count() > 0) {
		for (int i = 0; i < svcDesc->method_count(); i++) {
			const MethodDescriptor* methodDesc = svcDesc->method(i);
			printer.Print(
			    "\t} else if (methodName.compare(\"$methodName$\") == 0) {\n"
			    "\t\tif (in != NULL) delete(($inType$*)in);\n"
			    "\t\tif (out != NULL) delete(($outType$*)out);\n",
			    "inType", methodDesc->input_type()->name(),
			    "outType", methodDesc->output_type()->name(),
			    "methodName", methodDesc->name()
			);
		}
	}
	printer.Print("\t}\n}\n");
}

void ServiceGeneratorCPP::writeServiceStubImpl(io::Printer& printer, const ServiceDescriptor* svcDesc) const {
	if (svcDesc->method_count() > 0) {
		for (int i = 0; i < svcDesc->method_count(); i++) {

			const MethodDescriptor* methodDesc = svcDesc->method(i);
			printer.Print(
			    "$outType$* $className$Stub",
			    "className", svcDesc->name(),
			    "outType", methodDesc->output_type()->name());

			printer.Print(
			    "::$methodName$($inType$* in) {\n"
			    "\tvoid* out = NULL;\n"
			    "\tcallStubMethod(\"$methodName$\", in, \"$inType$\", out, \"$outType$\");\n"
			    "\treturn ($outType$*)out;\n"
			    "}\n",
			    "inType", methodDesc->input_type()->name(),
			    "methodName", methodDesc->name(),
			    "outType", methodDesc->output_type()->name()
			);
		}
	}
}

}

int main(int argc, char* argv[]) {
	umundo::ServiceGeneratorCPP generator;
	return google::protobuf::compiler::PluginMain(argc, argv, &generator);
}
<commit_msg>Support for light-weight reflection with services<commit_after>/**
 *  @file
 *  @author     2012 Stefan Radomski (stefan.radomski@cs.tu-darmstadt.de)
 *  @copyright  Simplified BSD
 *
 *  @cond
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the FreeBSD license as published by the FreeBSD
 *  project.
 *
 *  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.
 *
 *  You should have received a copy of the FreeBSD license along with this
 *  program. If not, see <http://www.opensource.org/licenses/bsd-license>.
 *  @endcond
 */

#include "umundo/protoc-rpc/ServiceGeneratorCPP.h"

#include <set>
#include <iostream>

#include <google/protobuf/compiler/plugin.h>
#include <google/protobuf/compiler/cpp/cpp_file.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/descriptor.pb.h>

namespace umundo {

using namespace google::protobuf::compiler::cpp;

bool ServiceGeneratorCPP::Generate(const FileDescriptor* file,
                                   const string& parameter,
                                   GeneratorContext* generator_context,
                                   string* error) const {
	vector<pair<string, string> > options;
	ParseGeneratorParameter(parameter, &options);

	string dllexport_decl;
	for (size_t i = 0; i < options.size(); i++) {
		if (options[i].first == "dllexport_decl") {
			dllexport_decl = options[i].second;
		} else {
			*error = "Unknown generator option: " + options[i].first;
			return false;
		}
	}

	string basename = StripProto(file->name());
	string filenameID = FilenameIdentifier(file->name());

	// Generate header.
	{
		scoped_ptr<io::ZeroCopyOutputStream> output(generator_context->Open(basename + ".rpc.pb.h"));
		io::Printer printer(output.get(), '$');

		// header prolog
		printer.Print(
		    "// Generated by the umundo protocol buffer compiler. DO NOT EDIT!\n"
		    "// source: $filename$\n\n"
		    "#ifndef __PROTOBUF_$filename_identifier$\n"
		    "#define __PROTOBUF_$filename_identifier$\n\n"
		    "#include <umundo/rpc.h>\n"
		    "#include \"$basename$.pb.h\" // generated by protoc\n"
		    "#include \"$basename$.rpc.pb.h\" // generated by protoc\n",

		    "basename", basename,
		    "filename", file->name(),
		    "filename_identifier", filenameID);

		if (file->dependency_count() > 0) {
			for (int i = 0; i < file->dependency_count(); i++) {
				const FileDescriptor* fileDesc = file->dependency(i);
				printer.Print("#include \"$dependency$.pb.h\" // generated by protoc\n", "dependency", StripProto(fileDesc->name()));
			}
		}

		printer.Print("\n\nnamespace umundo {\n\n");

		if (file->service_count() > 0) {
			for (int i = 0; i < file->service_count(); i++) {
				const ServiceDescriptor* svcDesc = file->service(i);
				writeServiceStubHeader(printer, svcDesc);
				printer.Print("\n");
				writeServiceHeader(printer, svcDesc);
				printer.Print("\n\n");
			}
		}

		// header epilog
		printer.Print(
		    "\n}\n"
		    "#endif\n");
	}

	// Generate cc file.
	{
		scoped_ptr<io::ZeroCopyOutputStream> output(generator_context->Open(basename + ".rpc.pb.cc"));
		io::Printer printer(output.get(), '$');

		if (file->service_count() > 0) {
			// implementation prolog
			printer.Print(
			    "#include \"umundo/rpc/Service.h\"\n"
			    "#include \"umundo/rpc/ServiceManager.h\"\n"
			    "#include \"$basename$.rpc.pb.h\"\n\n"
			    "namespace umundo {\n\n",
			    "basename", basename
			);

			for (int i = 0; i < file->service_count(); i++) {
				const ServiceDescriptor* svcDesc = file->service(i);
				writeServiceImplConstructor(printer, svcDesc);
				printer.Print("\n");
				writeServiceImplDispatcher(printer, svcDesc);
				printer.Print("\n");
				writeServiceImplCleanUp(printer, svcDesc);
				printer.Print("\n");
				writeServiceStubImpl(printer, svcDesc);
				printer.Print("\n\n");
			}
		}

		if (file->service_count() > 0) {
			// implementation epilog
			printer.Print("\n}\n");
		}
	}

	return true;

}

void ServiceGeneratorCPP::writeServiceStubHeader(io::Printer& printer, const ServiceDescriptor* svcDesc) const {
	printer.Print(
	    "class $svcName$Stub : public ServiceStub {\n"
	    "public:\n"
	    "\t$svcName$Stub(ServiceDescription*);\n",
	    "svcName", svcDesc->name()
	);

	if (svcDesc->method_count() > 0) {
		for (int i = 0; i < svcDesc->method_count(); i++) {
			const MethodDescriptor* methodDesc = svcDesc->method(i);
			printer.Print("\t$outType$* $methodName$($inType$*);\n",
			              "inType", container(methodDesc->input_type())->name(),
			              "methodName", methodDesc->name(),
			              "outType", container(methodDesc->output_type())->name()
			             );
		}
	}
	printer.Print("};\n");
}

void ServiceGeneratorCPP::writeServiceHeader(io::Printer &printer, const ServiceDescriptor* svcDesc) const {
	printer.Print(
	    "class $svcName$Base : public Service {\n"
	    "public:\n"
	    "\t$svcName$Base();\n",
	    "svcName", svcDesc->name()
	);

	if (svcDesc->method_count() > 0) {
		for (int i = 0; i < svcDesc->method_count(); i++) {
			const MethodDescriptor* methodDesc = svcDesc->method(i);
			printer.Print("\tvirtual $outType$* $methodName$($inType$*) = 0;\n",
			              "inType", container(methodDesc->input_type())->name(),
			              "methodName", methodDesc->name(),
			              "outType", container(methodDesc->output_type())->name()
			             );
		}

		printer.Print(
		    "protected:\n"
		    "\tvoid callMethod(string&, void*, string&, void*&, string&);\n"
		    "\tvoid cleanUpObjects(string&, void*, void*);\n"
		);
	}
	printer.Print("};\n");
}

const Descriptor* ServiceGeneratorCPP::container(const Descriptor* desc) {
//	fprintf(stderr, "checking %s\n", desc->name().c_str());
	while(desc->containing_type() != NULL) {
		desc = desc->containing_type();
//		fprintf(stderr, "\t-> %s\n", desc->name().c_str());
	}
	return desc;
}

void ServiceGeneratorCPP::writeServiceImplConstructor(io::Printer& printer, const ServiceDescriptor* svcDesc) const {

	std::set<string> inTypes;
	std::set<string> outTypes;
	std::set<string>::iterator inTypeIter;
	std::set<string>::iterator outTypeIter;

	if (svcDesc->method_count() > 0) {
		for (int i = 0; i < svcDesc->method_count(); i++) {
			const MethodDescriptor* methodDesc = svcDesc->method(i);
			inTypes.insert(methodDesc->input_type()->name());
			outTypes.insert(methodDesc->output_type()->name());
		}
	}

	printer.Print(
	    "$className$Stub::$className$Stub(ServiceDescription* svcDesc) : ServiceStub(svcDesc)  {\n"
	    "\t_serviceName = \"$className$\";\n",
	    "className", svcDesc->name()
	);

	// register intypes at publisher for stub, outtypes at subscriber
	for (inTypeIter = inTypes.begin(); inTypeIter != inTypes.end(); inTypeIter++) {
		printer.Print(
		    "\t_rpcPub->registerType(\"$inType$\", new $inType$());\n",
		    "inType", (*inTypeIter)
		);
	}
	for (outTypeIter = outTypes.begin(); outTypeIter != outTypes.end(); outTypeIter++) {
		printer.Print(
		    "\t_rpcSub->registerType(\"$outType$\", new $outType$());\n",
		    "outType", (*outTypeIter)
		);
	}

	printer.Print("}\n\n");

	printer.Print(
	    "$className$Base::$className$Base() {\n"
	    "\t_serviceName = \"$className$\";\n",
	    "className", svcDesc->name()
	);

	// register intypes at sublisher for impl, outtypes at publisher
	for (inTypeIter = inTypes.begin(); inTypeIter != inTypes.end(); inTypeIter++) {
		printer.Print(
		    "\t_rpcSub->registerType(\"$inType$\", new $inType$());\n",
		    "inType", (*inTypeIter)
		);
	}
	for (outTypeIter = outTypes.begin(); outTypeIter != outTypes.end(); outTypeIter++) {
		printer.Print(
		    "\t_rpcPub->registerType(\"$outType$\", new $outType$());\n",
		    "outType", (*outTypeIter)
		);
	}

	printer.Print("}\n");

}

void ServiceGeneratorCPP::writeServiceImplDispatcher(io::Printer& printer, const ServiceDescriptor* svcDesc) const {

	printer.Print(
	    "void $className$Base::callMethod(string& methodName, void* in, string& inType, void* &out, string& outType) {\n"
	    "\tif (false) {\n",
	    "className", svcDesc->name()
	);

	if (svcDesc->method_count() > 0) {
		for (int i = 0; i < svcDesc->method_count(); i++) {
			const MethodDescriptor* methodDesc = svcDesc->method(i);
			printer.Print(
			    "\t} else if (methodName.compare(\"$methodName$\") == 0) {\n"
			    "\t\tif (outType.length() == 0) { outType = \"$outType$\"; }\n"
			    "\t\tif (inType.length() == 0) { inType = \"$inType$\"; }\n"
			    "\t\tout = (void*)$methodName$(($inType$*)in);\n",
			    "outType", methodDesc->output_type()->name(),
			    "inType", methodDesc->input_type()->name(),
			    "methodName", methodDesc->name()
			);
		}
	}
	printer.Print("\t}\n}\n");
}

void ServiceGeneratorCPP::writeServiceImplCleanUp(io::Printer& printer, const ServiceDescriptor* svcDesc) const {
	printer.Print(
	    "void $className$Base::cleanUpObjects(string& methodName, void* in, void* out) {\n"
	    "\tif (false) {\n",
	    "className", svcDesc->name()
	);

	if (svcDesc->method_count() > 0) {
		for (int i = 0; i < svcDesc->method_count(); i++) {
			const MethodDescriptor* methodDesc = svcDesc->method(i);
			printer.Print(
			    "\t} else if (methodName.compare(\"$methodName$\") == 0) {\n"
			    "\t\tif (in != NULL) delete(($inType$*)in);\n"
			    "\t\tif (out != NULL) delete(($outType$*)out);\n",
			    "inType", methodDesc->input_type()->name(),
			    "outType", methodDesc->output_type()->name(),
			    "methodName", methodDesc->name()
			);
		}
	}
	printer.Print("\t}\n}\n");
}

void ServiceGeneratorCPP::writeServiceStubImpl(io::Printer& printer, const ServiceDescriptor* svcDesc) const {
	if (svcDesc->method_count() > 0) {
		for (int i = 0; i < svcDesc->method_count(); i++) {

			const MethodDescriptor* methodDesc = svcDesc->method(i);
			printer.Print(
			    "$outType$* $className$Stub",
			    "className", svcDesc->name(),
			    "outType", methodDesc->output_type()->name());

			printer.Print(
			    "::$methodName$($inType$* in) {\n"
			    "\tvoid* out = NULL;\n"
			    "\tcallStubMethod(\"$methodName$\", in, \"$inType$\", out, \"$outType$\");\n"
			    "\treturn ($outType$*)out;\n"
			    "}\n",
			    "inType", methodDesc->input_type()->name(),
			    "methodName", methodDesc->name(),
			    "outType", methodDesc->output_type()->name()
			);
		}
	}
}

}

int main(int argc, char* argv[]) {
	umundo::ServiceGeneratorCPP generator;
	return google::protobuf::compiler::PluginMain(argc, argv, &generator);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: colorcfg.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 13:44:14 $
 *
 *  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
 *
 ************************************************************************/
#ifndef INCLUDED_SVTOOLS_COLORCFG_HXX
#define INCLUDED_SVTOOLS_COLORCFG_HXX

#ifndef INCLUDED_SVTDLLAPI_H
#include "svtools/svtdllapi.h"
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _SFXBRDCST_HXX
#include <svtools/brdcst.hxx>
#endif
#ifndef _SFXLSTNER_HXX
#include <svtools/lstner.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_OPTIONS_HXX
#include <svtools/options.hxx>
#endif

//-----------------------------------------------------------------------------
namespace svtools{
enum ColorConfigEntry
{
    DOCCOLOR            ,
    DOCBOUNDARIES       ,
    APPBACKGROUND       ,
    OBJECTBOUNDARIES    ,
    TABLEBOUNDARIES     ,
    FONTCOLOR           ,
    LINKS               ,
    LINKSVISITED        ,
    ANCHOR              ,
    SPELL         ,
    SMARTTAGS     ,
    WRITERTEXTGRID      ,
    WRITERFIELDSHADINGS ,
    WRITERIDXSHADINGS         ,
    WRITERDIRECTCURSOR        ,
    WRITERNOTESINDICATOR,
    WRITERSCRIPTINDICATOR,
    WRITERSECTIONBOUNDARIES,
    WRITERPAGEBREAKS,
    HTMLSGML            ,
    HTMLCOMMENT         ,
    HTMLKEYWORD         ,
    HTMLUNKNOWN         ,
    CALCGRID            ,
    CALCPAGEBREAK       ,
    CALCPAGEBREAKMANUAL,
    CALCPAGEBREAKAUTOMATIC,
    CALCDETECTIVE       ,
    CALCDETECTIVEERROR       ,
    CALCREFERENCE       ,
    CALCNOTESBACKGROUND     ,
    DRAWGRID            ,
    DRAWDRAWING         ,
    DRAWFILL            ,
    BASICIDENTIFIER,
    BASICCOMMENT   ,
    BASICNUMBER    ,
    BASICSTRING    ,
    BASICOPERATOR  ,
    BASICKEYWORD   ,
    BASICERROR   ,
    ColorConfigEntryCount
};
/* -----------------------------22.03.2002 15:36------------------------------

 ---------------------------------------------------------------------------*/
class ColorConfig_Impl;
struct ColorConfigValue
{

    sal_Bool    bIsVisible; //validity depends on the element type
    sal_Int32   nColor;
    ColorConfigValue() : bIsVisible(sal_False), nColor(0) {}
    sal_Bool operator !=(const ColorConfigValue& rCmp) const
        { return nColor != rCmp.nColor || bIsVisible != rCmp.bIsVisible;}
};
/* -----------------------------22.03.2002 15:36------------------------------

 ---------------------------------------------------------------------------*/
class SVT_DLLPUBLIC ColorConfig:
    public svt::detail::Options, public SfxBroadcaster, public SfxListener
{
    friend class ColorConfig_Impl;
private:
    static ColorConfig_Impl* m_pImpl;
public:
    ColorConfig();
    virtual ~ColorConfig();

    virtual void        Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

    // get the configured value - if bSmart is set the default color setting is provided
    // instead of the automatic color
    ColorConfigValue        GetColorValue(ColorConfigEntry eEntry, sal_Bool bSmart = sal_True)const;

    static Color            GetDefaultColor(ColorConfigEntry eEntry);
};
/* -----------------------------22.03.2002 15:31------------------------------

 ---------------------------------------------------------------------------*/
class SVT_DLLPUBLIC EditableColorConfig
{
    ColorConfig_Impl*   m_pImpl;
    sal_Bool            m_bModified;
public:
    EditableColorConfig();
    ~EditableColorConfig();

    ::com::sun::star::uno::Sequence< ::rtl::OUString >  GetSchemeNames() const;
    void                                                DeleteScheme(const ::rtl::OUString& rScheme );
    void                                                AddScheme(const ::rtl::OUString& rScheme );
    sal_Bool                                            LoadScheme(const ::rtl::OUString& rScheme );
    const ::rtl::OUString&                              GetCurrentSchemeName()const;
    void                        SetCurrentSchemeName(const ::rtl::OUString& rScheme);

    const ColorConfigValue&     GetColorValue(ColorConfigEntry eEntry)const;
    void                        SetColorValue(ColorConfigEntry eEntry, const ColorConfigValue& rValue);
    void                        SetModified();
    void                        ClearModified(){m_bModified = sal_False;}
    sal_Bool                    IsModified()const{return m_bModified;}
    void                        Commit();

    void                        DisableBroadcast();
    void                        EnableBroadcast();
};
}//namespace svtools
#endif

<commit_msg>INTEGRATION: CWS swnotescolor (1.3.154); FILE MERGED 2007/12/02 20:54:44 mod 1.3.154.1: remove note color indicator from Options - Appearance<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: colorcfg.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2008-03-18 16:43:40 $
 *
 *  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
 *
 ************************************************************************/
#ifndef INCLUDED_SVTOOLS_COLORCFG_HXX
#define INCLUDED_SVTOOLS_COLORCFG_HXX

#ifndef INCLUDED_SVTDLLAPI_H
#include "svtools/svtdllapi.h"
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _SFXBRDCST_HXX
#include <svtools/brdcst.hxx>
#endif
#ifndef _SFXLSTNER_HXX
#include <svtools/lstner.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_OPTIONS_HXX
#include <svtools/options.hxx>
#endif

//-----------------------------------------------------------------------------
namespace svtools{
enum ColorConfigEntry
{
    DOCCOLOR            ,
    DOCBOUNDARIES       ,
    APPBACKGROUND       ,
    OBJECTBOUNDARIES    ,
    TABLEBOUNDARIES     ,
    FONTCOLOR           ,
    LINKS               ,
    LINKSVISITED        ,
    ANCHOR              ,
    SPELL         ,
    SMARTTAGS     ,
    WRITERTEXTGRID      ,
    WRITERFIELDSHADINGS ,
    WRITERIDXSHADINGS         ,
    WRITERDIRECTCURSOR        ,
    WRITERSCRIPTINDICATOR,
    WRITERSECTIONBOUNDARIES,
    WRITERPAGEBREAKS,
    HTMLSGML            ,
    HTMLCOMMENT         ,
    HTMLKEYWORD         ,
    HTMLUNKNOWN         ,
    CALCGRID            ,
    CALCPAGEBREAK       ,
    CALCPAGEBREAKMANUAL,
    CALCPAGEBREAKAUTOMATIC,
    CALCDETECTIVE       ,
    CALCDETECTIVEERROR       ,
    CALCREFERENCE       ,
    CALCNOTESBACKGROUND     ,
    DRAWGRID            ,
    DRAWDRAWING         ,
    DRAWFILL            ,
    BASICIDENTIFIER,
    BASICCOMMENT   ,
    BASICNUMBER    ,
    BASICSTRING    ,
    BASICOPERATOR  ,
    BASICKEYWORD   ,
    BASICERROR   ,
    ColorConfigEntryCount
};
/* -----------------------------22.03.2002 15:36------------------------------

 ---------------------------------------------------------------------------*/
class ColorConfig_Impl;
struct ColorConfigValue
{

    sal_Bool    bIsVisible; //validity depends on the element type
    sal_Int32   nColor;
    ColorConfigValue() : bIsVisible(sal_False), nColor(0) {}
    sal_Bool operator !=(const ColorConfigValue& rCmp) const
        { return nColor != rCmp.nColor || bIsVisible != rCmp.bIsVisible;}
};
/* -----------------------------22.03.2002 15:36------------------------------

 ---------------------------------------------------------------------------*/
class SVT_DLLPUBLIC ColorConfig:
    public svt::detail::Options, public SfxBroadcaster, public SfxListener
{
    friend class ColorConfig_Impl;
private:
    static ColorConfig_Impl* m_pImpl;
public:
    ColorConfig();
    virtual ~ColorConfig();

    virtual void        Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

    // get the configured value - if bSmart is set the default color setting is provided
    // instead of the automatic color
    ColorConfigValue        GetColorValue(ColorConfigEntry eEntry, sal_Bool bSmart = sal_True)const;

    static Color            GetDefaultColor(ColorConfigEntry eEntry);
};
/* -----------------------------22.03.2002 15:31------------------------------

 ---------------------------------------------------------------------------*/
class SVT_DLLPUBLIC EditableColorConfig
{
    ColorConfig_Impl*   m_pImpl;
    sal_Bool            m_bModified;
public:
    EditableColorConfig();
    ~EditableColorConfig();

    ::com::sun::star::uno::Sequence< ::rtl::OUString >  GetSchemeNames() const;
    void                                                DeleteScheme(const ::rtl::OUString& rScheme );
    void                                                AddScheme(const ::rtl::OUString& rScheme );
    sal_Bool                                            LoadScheme(const ::rtl::OUString& rScheme );
    const ::rtl::OUString&                              GetCurrentSchemeName()const;
    void                        SetCurrentSchemeName(const ::rtl::OUString& rScheme);

    const ColorConfigValue&     GetColorValue(ColorConfigEntry eEntry)const;
    void                        SetColorValue(ColorConfigEntry eEntry, const ColorConfigValue& rValue);
    void                        SetModified();
    void                        ClearModified(){m_bModified = sal_False;}
    sal_Bool                    IsModified()const{return m_bModified;}
    void                        Commit();

    void                        DisableBroadcast();
    void                        EnableBroadcast();
};
}//namespace svtools
#endif

<|endoftext|>


<commit_before><commit_msg>WaE: compare unsigned values.<commit_after><|endoftext|>


<commit_before><commit_msg>fdo#50139 do not cut first character of field text<commit_after><|endoftext|>