<commit_before>//===-- NativeProcessProtocolTest.cpp ---------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Host/common/NativeProcessProtocol.h"
#include "llvm/Testing/Support/Error.h"
#include "gmock/gmock.h"

using namespace lldb_private;
using namespace lldb;
using namespace testing;

namespace {
class MockDelegate : public NativeProcessProtocol::NativeDelegate {
public:
  MOCK_METHOD1(InitializeDelegate, void(NativeProcessProtocol *Process));
  MOCK_METHOD2(ProcessStateChanged,
               void(NativeProcessProtocol *Process, StateType State));
  MOCK_METHOD1(DidExec, void(NativeProcessProtocol *Process));
};

class MockProcess : public NativeProcessProtocol {
public:
  MockProcess(NativeDelegate &Delegate, const ArchSpec &Arch,
              lldb::pid_t Pid = 1)
      : NativeProcessProtocol(Pid, -1, Delegate), Arch(Arch) {}

  MOCK_METHOD1(Resume, Status(const ResumeActionList &ResumeActions));
  MOCK_METHOD0(Halt, Status());
  MOCK_METHOD0(Detach, Status());
  MOCK_METHOD1(Signal, Status(int Signo));
  MOCK_METHOD0(Kill, Status());
  MOCK_METHOD3(AllocateMemory,
               Status(size_t Size, uint32_t Permissions, addr_t &Addr));
  MOCK_METHOD1(DeallocateMemory, Status(addr_t Addr));
  MOCK_METHOD0(GetSharedLibraryInfoAddress, addr_t());
  MOCK_METHOD0(UpdateThreads, size_t());
  MOCK_CONST_METHOD0(GetAuxvData,
                     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>());
  MOCK_METHOD2(GetLoadedModuleFileSpec,
               Status(const char *ModulePath, FileSpec &Spec));
  MOCK_METHOD2(GetFileLoadAddress,
               Status(const llvm::StringRef &FileName, addr_t &Addr));

  const ArchSpec &GetArchitecture() const override { return Arch; }
  Status SetBreakpoint(lldb::addr_t Addr, uint32_t Size,
                       bool Hardware) override {
    if (Hardware)
      return SetHardwareBreakpoint(Addr, Size);
    else
      return SetSoftwareBreakpoint(Addr, Size);
  }

  // Redirect base class Read/Write Memory methods to functions whose signatures
  // are more mock-friendly.
  Status ReadMemory(addr_t Addr, void *Buf, size_t Size,
                    size_t &BytesRead) override;
  Status WriteMemory(addr_t Addr, const void *Buf, size_t Size,
                     size_t &BytesWritten) override;

  MOCK_METHOD2(ReadMemory,
               llvm::Expected<std::vector<uint8_t>>(addr_t Addr, size_t Size));
  MOCK_METHOD2(WriteMemory,
               llvm::Expected<size_t>(addr_t Addr,
                                      llvm::ArrayRef<uint8_t> Data));

  using NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode;
  llvm::Expected<std::vector<uint8_t>> ReadMemoryWithoutTrap(addr_t Addr,
                                                             size_t Size);

private:
  ArchSpec Arch;
};

class FakeMemory {
public:
  FakeMemory(llvm::ArrayRef<uint8_t> Data) : Data(Data) {}
  llvm::Expected<std::vector<uint8_t>> Read(addr_t Addr, size_t Size);
  llvm::Expected<size_t> Write(addr_t Addr, llvm::ArrayRef<uint8_t> Chunk);

private:
  std::vector<uint8_t> Data;
};
} // namespace

Status MockProcess::ReadMemory(addr_t Addr, void *Buf, size_t Size,
                               size_t &BytesRead) {
  auto ExpectedMemory = ReadMemory(Addr, Size);
  if (!ExpectedMemory) {
    BytesRead = 0;
    return Status(ExpectedMemory.takeError());
  }
  BytesRead = ExpectedMemory->size();
  assert(BytesRead <= Size);
  std::memcpy(Buf, ExpectedMemory->data(), BytesRead);
  return Status();
}

Status MockProcess::WriteMemory(addr_t Addr, const void *Buf, size_t Size,
                                size_t &BytesWritten) {
  auto ExpectedBytes = WriteMemory(
      Addr, llvm::makeArrayRef(static_cast<const uint8_t *>(Buf), Size));
  if (!ExpectedBytes) {
    BytesWritten = 0;
    return Status(ExpectedBytes.takeError());
  }
  BytesWritten = *ExpectedBytes;
  return Status();
}

llvm::Expected<std::vector<uint8_t>>
MockProcess::ReadMemoryWithoutTrap(addr_t Addr, size_t Size) {
  std::vector<uint8_t> Data(Size, 0);
  size_t BytesRead;
  Status ST = NativeProcessProtocol::ReadMemoryWithoutTrap(
      Addr, Data.data(), Data.size(), BytesRead);
  if (ST.Fail())
    return ST.ToError();
  Data.resize(BytesRead);
  return std::move(Data);
}

llvm::Expected<std::vector<uint8_t>> FakeMemory::Read(addr_t Addr,
                                                      size_t Size) {
  if (Addr >= Data.size())
    return llvm::createStringError(llvm::inconvertibleErrorCode(),
                                   "Address out of range.");
  Size = std::min(Size, Data.size() - (size_t)Addr);
  return std::vector<uint8_t>(&Data[Addr], &Data[Addr + Size]);
}

llvm::Expected<size_t> FakeMemory::Write(addr_t Addr,
                                         llvm::ArrayRef<uint8_t> Chunk) {
  if (Addr >= Data.size())
    return llvm::createStringError(llvm::inconvertibleErrorCode(),
                                   "Address out of range.");
  size_t Size = std::min(Chunk.size(), Data.size() - (size_t)Addr);
  std::copy_n(Chunk.begin(), Size, &Data[Addr]);
  return Size;
}

TEST(NativeProcessProtocolTest, SetBreakpoint) {
  NiceMock<MockDelegate> DummyDelegate;
  MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux"));
  auto Trap = cantFail(Process.GetSoftwareBreakpointTrapOpcode(1));
  InSequence S;
  EXPECT_CALL(Process, ReadMemory(0x47, 1))
      .WillOnce(Return(ByMove(std::vector<uint8_t>{0xbb})));
  EXPECT_CALL(Process, WriteMemory(0x47, Trap)).WillOnce(Return(ByMove(1)));
  EXPECT_CALL(Process, ReadMemory(0x47, 1)).WillOnce(Return(ByMove(Trap)));
  EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(),
                    llvm::Succeeded());
}

TEST(NativeProcessProtocolTest, SetBreakpointFailRead) {
  NiceMock<MockDelegate> DummyDelegate;
  MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux"));
  EXPECT_CALL(Process, ReadMemory(0x47, 1))
      .WillOnce(Return(ByMove(
          llvm::createStringError(llvm::inconvertibleErrorCode(), "Foo"))));
  EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(),
                    llvm::Failed());
}

TEST(NativeProcessProtocolTest, SetBreakpointFailWrite) {
  NiceMock<MockDelegate> DummyDelegate;
  MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux"));
  auto Trap = cantFail(Process.GetSoftwareBreakpointTrapOpcode(1));
  InSequence S;
  EXPECT_CALL(Process, ReadMemory(0x47, 1))
      .WillOnce(Return(ByMove(std::vector<uint8_t>{0xbb})));
  EXPECT_CALL(Process, WriteMemory(0x47, Trap))
      .WillOnce(Return(ByMove(
          llvm::createStringError(llvm::inconvertibleErrorCode(), "Foo"))));
  EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(),
                    llvm::Failed());
}

TEST(NativeProcessProtocolTest, SetBreakpointFailVerify) {
  NiceMock<MockDelegate> DummyDelegate;
  MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux"));
  auto Trap = cantFail(Process.GetSoftwareBreakpointTrapOpcode(1));
  InSequence S;
  EXPECT_CALL(Process, ReadMemory(0x47, 1))
      .WillOnce(Return(ByMove(std::vector<uint8_t>{0xbb})));
  EXPECT_CALL(Process, WriteMemory(0x47, Trap)).WillOnce(Return(ByMove(1)));
  EXPECT_CALL(Process, ReadMemory(0x47, 1))
      .WillOnce(Return(ByMove(
          llvm::createStringError(llvm::inconvertibleErrorCode(), "Foo"))));
  EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(),
                    llvm::Failed());
}

TEST(NativeProcessProtocolTest, ReadMemoryWithoutTrap) {
  NiceMock<MockDelegate> DummyDelegate;
  MockProcess Process(DummyDelegate, ArchSpec("aarch64-pc-linux"));
  FakeMemory M{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}};
  EXPECT_CALL(Process, ReadMemory(_, _))
      .WillRepeatedly(Invoke(&M, &FakeMemory::Read));
  EXPECT_CALL(Process, WriteMemory(_, _))
      .WillRepeatedly(Invoke(&M, &FakeMemory::Write));

  EXPECT_THAT_ERROR(Process.SetBreakpoint(0x4, 0, false).ToError(),
                    llvm::Succeeded());
  EXPECT_THAT_EXPECTED(
      Process.ReadMemoryWithoutTrap(0, 10),
      llvm::HasValue(std::vector<uint8_t>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}));
  EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(0, 6),
                       llvm::HasValue(std::vector<uint8_t>{0, 1, 2, 3, 4, 5}));
  EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(6, 4),
                       llvm::HasValue(std::vector<uint8_t>{6, 7, 8, 9}));
  EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(6, 2),
                       llvm::HasValue(std::vector<uint8_t>{6, 7}));
  EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(4, 2),
                       llvm::HasValue(std::vector<uint8_t>{4, 5}));
}
<commit_msg>Fix assertion failure in NativeProcessProtocolTest<commit_after>//===-- NativeProcessProtocolTest.cpp ---------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Host/common/NativeProcessProtocol.h"
#include "llvm/Testing/Support/Error.h"
#include "gmock/gmock.h"

using namespace lldb_private;
using namespace lldb;
using namespace testing;

namespace {
class MockDelegate : public NativeProcessProtocol::NativeDelegate {
public:
  MOCK_METHOD1(InitializeDelegate, void(NativeProcessProtocol *Process));
  MOCK_METHOD2(ProcessStateChanged,
               void(NativeProcessProtocol *Process, StateType State));
  MOCK_METHOD1(DidExec, void(NativeProcessProtocol *Process));
};

class MockProcess : public NativeProcessProtocol {
public:
  MockProcess(NativeDelegate &Delegate, const ArchSpec &Arch,
              lldb::pid_t Pid = 1)
      : NativeProcessProtocol(Pid, -1, Delegate), Arch(Arch) {}

  MOCK_METHOD1(Resume, Status(const ResumeActionList &ResumeActions));
  MOCK_METHOD0(Halt, Status());
  MOCK_METHOD0(Detach, Status());
  MOCK_METHOD1(Signal, Status(int Signo));
  MOCK_METHOD0(Kill, Status());
  MOCK_METHOD3(AllocateMemory,
               Status(size_t Size, uint32_t Permissions, addr_t &Addr));
  MOCK_METHOD1(DeallocateMemory, Status(addr_t Addr));
  MOCK_METHOD0(GetSharedLibraryInfoAddress, addr_t());
  MOCK_METHOD0(UpdateThreads, size_t());
  MOCK_CONST_METHOD0(GetAuxvData,
                     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>());
  MOCK_METHOD2(GetLoadedModuleFileSpec,
               Status(const char *ModulePath, FileSpec &Spec));
  MOCK_METHOD2(GetFileLoadAddress,
               Status(const llvm::StringRef &FileName, addr_t &Addr));

  const ArchSpec &GetArchitecture() const override { return Arch; }
  Status SetBreakpoint(lldb::addr_t Addr, uint32_t Size,
                       bool Hardware) override {
    if (Hardware)
      return SetHardwareBreakpoint(Addr, Size);
    else
      return SetSoftwareBreakpoint(Addr, Size);
  }

  // Redirect base class Read/Write Memory methods to functions whose signatures
  // are more mock-friendly.
  Status ReadMemory(addr_t Addr, void *Buf, size_t Size,
                    size_t &BytesRead) override;
  Status WriteMemory(addr_t Addr, const void *Buf, size_t Size,
                     size_t &BytesWritten) override;

  MOCK_METHOD2(ReadMemory,
               llvm::Expected<std::vector<uint8_t>>(addr_t Addr, size_t Size));
  MOCK_METHOD2(WriteMemory,
               llvm::Expected<size_t>(addr_t Addr,
                                      llvm::ArrayRef<uint8_t> Data));

  using NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode;
  llvm::Expected<std::vector<uint8_t>> ReadMemoryWithoutTrap(addr_t Addr,
                                                             size_t Size);

private:
  ArchSpec Arch;
};

class FakeMemory {
public:
  FakeMemory(llvm::ArrayRef<uint8_t> Data) : Data(Data) {}
  llvm::Expected<std::vector<uint8_t>> Read(addr_t Addr, size_t Size);
  llvm::Expected<size_t> Write(addr_t Addr, llvm::ArrayRef<uint8_t> Chunk);

private:
  std::vector<uint8_t> Data;
};
} // namespace

Status MockProcess::ReadMemory(addr_t Addr, void *Buf, size_t Size,
                               size_t &BytesRead) {
  auto ExpectedMemory = ReadMemory(Addr, Size);
  if (!ExpectedMemory) {
    BytesRead = 0;
    return Status(ExpectedMemory.takeError());
  }
  BytesRead = ExpectedMemory->size();
  assert(BytesRead <= Size);
  std::memcpy(Buf, ExpectedMemory->data(), BytesRead);
  return Status();
}

Status MockProcess::WriteMemory(addr_t Addr, const void *Buf, size_t Size,
                                size_t &BytesWritten) {
  auto ExpectedBytes = WriteMemory(
      Addr, llvm::makeArrayRef(static_cast<const uint8_t *>(Buf), Size));
  if (!ExpectedBytes) {
    BytesWritten = 0;
    return Status(ExpectedBytes.takeError());
  }
  BytesWritten = *ExpectedBytes;
  return Status();
}

llvm::Expected<std::vector<uint8_t>>
MockProcess::ReadMemoryWithoutTrap(addr_t Addr, size_t Size) {
  std::vector<uint8_t> Data(Size, 0);
  size_t BytesRead;
  Status ST = NativeProcessProtocol::ReadMemoryWithoutTrap(
      Addr, Data.data(), Data.size(), BytesRead);
  if (ST.Fail())
    return ST.ToError();
  Data.resize(BytesRead);
  return std::move(Data);
}

llvm::Expected<std::vector<uint8_t>> FakeMemory::Read(addr_t Addr,
                                                      size_t Size) {
  if (Addr >= Data.size())
    return llvm::createStringError(llvm::inconvertibleErrorCode(),
                                   "Address out of range.");
  Size = std::min(Size, Data.size() - (size_t)Addr);
  auto Begin = std::next(Data.begin(), Addr);
  return std::vector<uint8_t>(Begin, std::next(Begin, Size));
}

llvm::Expected<size_t> FakeMemory::Write(addr_t Addr,
                                         llvm::ArrayRef<uint8_t> Chunk) {
  if (Addr >= Data.size())
    return llvm::createStringError(llvm::inconvertibleErrorCode(),
                                   "Address out of range.");
  size_t Size = std::min(Chunk.size(), Data.size() - (size_t)Addr);
  std::copy_n(Chunk.begin(), Size, &Data[Addr]);
  return Size;
}

TEST(NativeProcessProtocolTest, SetBreakpoint) {
  NiceMock<MockDelegate> DummyDelegate;
  MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux"));
  auto Trap = cantFail(Process.GetSoftwareBreakpointTrapOpcode(1));
  InSequence S;
  EXPECT_CALL(Process, ReadMemory(0x47, 1))
      .WillOnce(Return(ByMove(std::vector<uint8_t>{0xbb})));
  EXPECT_CALL(Process, WriteMemory(0x47, Trap)).WillOnce(Return(ByMove(1)));
  EXPECT_CALL(Process, ReadMemory(0x47, 1)).WillOnce(Return(ByMove(Trap)));
  EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(),
                    llvm::Succeeded());
}

TEST(NativeProcessProtocolTest, SetBreakpointFailRead) {
  NiceMock<MockDelegate> DummyDelegate;
  MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux"));
  EXPECT_CALL(Process, ReadMemory(0x47, 1))
      .WillOnce(Return(ByMove(
          llvm::createStringError(llvm::inconvertibleErrorCode(), "Foo"))));
  EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(),
                    llvm::Failed());
}

TEST(NativeProcessProtocolTest, SetBreakpointFailWrite) {
  NiceMock<MockDelegate> DummyDelegate;
  MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux"));
  auto Trap = cantFail(Process.GetSoftwareBreakpointTrapOpcode(1));
  InSequence S;
  EXPECT_CALL(Process, ReadMemory(0x47, 1))
      .WillOnce(Return(ByMove(std::vector<uint8_t>{0xbb})));
  EXPECT_CALL(Process, WriteMemory(0x47, Trap))
      .WillOnce(Return(ByMove(
          llvm::createStringError(llvm::inconvertibleErrorCode(), "Foo"))));
  EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(),
                    llvm::Failed());
}

TEST(NativeProcessProtocolTest, SetBreakpointFailVerify) {
  NiceMock<MockDelegate> DummyDelegate;
  MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux"));
  auto Trap = cantFail(Process.GetSoftwareBreakpointTrapOpcode(1));
  InSequence S;
  EXPECT_CALL(Process, ReadMemory(0x47, 1))
      .WillOnce(Return(ByMove(std::vector<uint8_t>{0xbb})));
  EXPECT_CALL(Process, WriteMemory(0x47, Trap)).WillOnce(Return(ByMove(1)));
  EXPECT_CALL(Process, ReadMemory(0x47, 1))
      .WillOnce(Return(ByMove(
          llvm::createStringError(llvm::inconvertibleErrorCode(), "Foo"))));
  EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(),
                    llvm::Failed());
}

TEST(NativeProcessProtocolTest, ReadMemoryWithoutTrap) {
  NiceMock<MockDelegate> DummyDelegate;
  MockProcess Process(DummyDelegate, ArchSpec("aarch64-pc-linux"));
  FakeMemory M{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}};
  EXPECT_CALL(Process, ReadMemory(_, _))
      .WillRepeatedly(Invoke(&M, &FakeMemory::Read));
  EXPECT_CALL(Process, WriteMemory(_, _))
      .WillRepeatedly(Invoke(&M, &FakeMemory::Write));

  EXPECT_THAT_ERROR(Process.SetBreakpoint(0x4, 0, false).ToError(),
                    llvm::Succeeded());
  EXPECT_THAT_EXPECTED(
      Process.ReadMemoryWithoutTrap(0, 10),
      llvm::HasValue(std::vector<uint8_t>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}));
  EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(0, 6),
                       llvm::HasValue(std::vector<uint8_t>{0, 1, 2, 3, 4, 5}));
  EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(6, 4),
                       llvm::HasValue(std::vector<uint8_t>{6, 7, 8, 9}));
  EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(6, 2),
                       llvm::HasValue(std::vector<uint8_t>{6, 7}));
  EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(4, 2),
                       llvm::HasValue(std::vector<uint8_t>{4, 5}));
}
<|endoftext|>


<commit_before>#include "include/Media.h"
#include <iostream>

/**< ShapeMedia */
Shape * ShapeMedia::getShape(){
    return shape;
}

double ShapeMedia::area() const{
    return shape->area();
}

double ShapeMedia::perimeter() const{
    return shape->perimeter();
}

/**< ComboMedia */
ComboMedia::ComboMedia() {
    std::vector<Media *> instance;
    medias = instance;
}

void ComboMedia::add(Media * ma){
    medias.push_back(ma);
}

std::vector<Media *> ComboMedia::getMedias(){
    return medias;
}

double ComboMedia::area() const{
    double total = 0;

    for (Media * mp : medias)
        total += mp->area();

    return total;
}

double ComboMedia::perimeter() const{
    double total = 0;

    for (Media * mp : medias)
        total += mp->perimeter();

    return total;
}

<commit_msg>Delete Media.cpp<commit_after><|endoftext|>


<commit_before>#pragma once

#include "Tools/NoCreateU.hpp"
#include <string>
#include <vector>

namespace proZPRd
{
	/**
		Klasa opisująca podstawowe operacje na pliku

		W chwili obecnej zakładam, że będzie zawierała wyłącznie metody statyczne itp, więc nie ma konstruktorów, destruktorów itp. Zabronienie tworzenia obiektów klasy gwarantuje dziedziczenie po NoCreateU
	*/
	class File : public Tools::NoCreateU
	{
		public:

			typedef std::vector<std::string> Lines_t;

			/**
				Funkcja ma sprawdzić czy podany plik istnieje i czy jest plikiem.

				Jeśli istnieje i jest plikiem - zwraca true
				Jeśli nie istnieje lub nie jest plikiem - zwraca false
			*/
			static bool Exists(const std::string & FileName);

			/**
				Funkcja ma wczytać cały plik o podanej nazwie do pamięci i zwrócić go w postaci std::string.
				Jeśli plik nie istnieje ma rzucić Tool::Exception z odpowiednimi parametrami
			*/
			static std::string ToString(const std::string & FileName);

			/**
				Funkcja wczytuje cały plik o podanej nazwie do pamięci i zwraca go w postaci Lines_t, czyli wektora zawierającego linie pliku
			*/

			static Lines_t GetLines(const std::string & FileName);

			struct FileStruct
			{
				std::string Name;
				std::string Extension;
			};
			/**
				Funkcja ma podzielić nazwę pliku na nazwę i rozszerzenie.
				Jeśli plik nie ma rozszerzenia, pozostaje ono puste.
			*/
			static FileStruct SplitFileName(const std::string & FileName);

	};
}<commit_msg>Porządki w proZPRd/File.hpp<commit_after>#pragma once

#include "Tools/NoCreateU.hpp"
#include <string>
#include <vector>

namespace proZPRd
{
	/**
		Klasa opisująca podstawowe operacje na pliku

		W chwili obecnej zakładam, że będzie zawierała wyłącznie metody statyczne itp, więc nie ma konstruktorów, destruktorów itp. Zabronienie tworzenia obiektów klasy gwarantuje dziedziczenie po NoCreateU
	*/
	class File : public Tools::NoCreateU
	{
		public:
			/**
				Funkcja ma sprawdzić czy podany plik istnieje i czy jest plikiem.

				Jeśli istnieje i jest plikiem - zwraca true
				Jeśli nie istnieje lub nie jest plikiem - zwraca false
			*/
			static bool Exists(const std::string & FileName);

			/**
				Funkcja ma wczytać cały plik o podanej nazwie do pamięci i zwrócić go w postaci std::string.
				Jeśli plik nie istnieje ma rzucić Tool::Exception z odpowiednimi parametrami
			*/
			static std::string ToString(const std::string & FileName);

			/**
				Funkcja wczytuje cały plik o podanej nazwie do pamięci i zwraca go w postaci Lines_t, czyli wektora zawierającego linie pliku
			*/
			typedef std::vector<std::string> Lines_t;
			static Lines_t GetLines(const std::string & FileName);

			/**
				Funkcja ma podzielić nazwę pliku na nazwę i rozszerzenie.
				Jeśli plik nie ma rozszerzenia, pozostaje ono puste.
			*/
			struct FileStruct
			{
				std::string Name;
				std::string Extension;
			};
			static FileStruct SplitFileName(const std::string & FileName);

	};
}<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2018 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "Renderer.h"

#include "common/FrameBuffer.h"
#include "visitor/MarkAllAsModified.h"
#include "visitor/VerifyNodes.h"

namespace ospray {
  namespace sg {

    static std::vector<std::string> globalWhiteList = {
      std::string("scivis"),
      std::string("pathtracer"),
      std::string("ao"),
      std::string("raycast"),
      std::string("raycast_vertexColor"),
      std::string("raycast_dPds"),
      std::string("raycast_dPdt"),
      std::string("raycast_Ng"),
      std::string("raycast_Ns"),
      std::string("backfacing_Ng"),
      std::string("backfacing_Ns"),
      std::string("primID"),
      std::string("geomID"),
      std::string("instID"),
      std::string("testFrame")
    };

    std::vector<std::string> Renderer::globalRendererTypeWhiteList()
    {
      return globalWhiteList;
    }

    void Renderer::setGlobalRendererTypeWhiteList(std::vector<std::string> list)
    {
      globalWhiteList = list;
    }

    Renderer::Renderer()
    {
      std::string defaultRendererType =
          globalWhiteList.empty() ? "scivis" : globalWhiteList[0];

      createChild("rendererType", "string", defaultRendererType,
                  NodeFlags::required |
                  NodeFlags::gui_combo,
                  "scivis: standard whitted style ray tracer. "
                  "pathtracer/pt: photo-realistic path tracer");

      std::vector<Any> whiteList;
      for (auto &v : globalWhiteList)
        whiteList.push_back(v);

      child("rendererType").setWhiteList(whiteList);
      createChild("world",
                  "Model").setDocumentation("model containing scene objects");
      createChild("camera", "PerspectiveCamera");
      createChild("frameBuffer", "FrameBuffer");
      createChild("lights");

      createChild("bgColor", "vec3f", vec3f(0.15f, 0.15f, 0.15f),
                  NodeFlags::required |
                  NodeFlags::gui_color);

      createChild("spp", "int", 1,
                  NodeFlags::required | NodeFlags::gui_slider,
                  "the number of samples rendered per pixel. The higher "
                  "the number, the smoother the resulting image.");
      child("spp").setMinMax(-8,128);

      createChild("minContribution", "float", 0.001f,
                  NodeFlags::required |
                  NodeFlags::gui_slider,
                  "sample contributions below this value will be neglected"
                  " to speed-up rendering.");
      child("minContribution").setMinMax(0.f, 0.1f);

      createChild("maxContribution", "float", 5.f,
                  NodeFlags::required |
                  NodeFlags::gui_slider,
                  "sample contributions above this value will be ignored."
                  "  This reduces bright dots appearing in images");
      child("maxContribution").setMinMax(1e-5f, 1e5f);

      createChild("varianceThreshold", "float", 0.f,
                  NodeFlags::required |
                  NodeFlags::gui_slider,
                  "the percent (%) threshold of pixel difference to enable"
                  " tile rendering early termination.");
      child("varianceThreshold").setMinMax(0.f, 25.f);

      //TODO: move these to seperate SciVisRenderer
      createChild("shadowsEnabled", "bool", true);
      createChild("maxDepth", "int", 5,
                  NodeFlags::required | NodeFlags::valid_min_max,
                  "maximum number of ray bounces").setMinMax(0,999);
      createChild("aoSamples", "int", 1,
                  NodeFlags::required |
                  NodeFlags::gui_slider,
                  "AO samples per frame.").setMinMax(0,128);

      createChild("aoDistance", "float", 10000.f,
                  NodeFlags::required,
                  "maximum distance ao rays will trace to."
                  " Useful if you do not want a large interior of a"
                  " building to be completely black from occlusion.");
      child("aoDistance").setMinMax(1e-20f, 1e20f);

      createChild("epsilon", "float", 1e-3f,
                  NodeFlags::required | NodeFlags::valid_min_max,
                  "epsilon step for secondary ray generation.  Adjust"
                  " if you see speckles or a lack of lighting.");
      child("epsilon").setMinMax(1e-20f, 1e20f);
      createChild("autoEpsilon", "bool", true, NodeFlags::required,
        "automatically adjust epsilon step");

      createChild("oneSidedLighting", "bool", true, NodeFlags::required);
      createChild("aoTransparencyEnabled", "bool", true, NodeFlags::required);

      createChild("backplate", "Texture2D");
      auto backplate = child("backplate").nodeAs<Texture2D>();
      backplate->size.x = 1;
      backplate->size.y = 1;
      backplate->channels = 3;
      backplate->preferLinear = true;
      backplate->depth = 4;
      const size_t stride = backplate->size.x * backplate->channels * backplate->depth;
      backplate->data = malloc(sizeof(unsigned char) * backplate->size.y * stride);
      vec3f bgColor = child("bgColor").valueAs<vec3f>();
      memcpy(backplate->data, &bgColor.x, backplate->channels*backplate->depth);
      createChild("useBackplate", "bool", true, NodeFlags::none, "use\
           backplate for path tracer");
    }

    Renderer::~Renderer()
    {
      if (lightsData)
        ospRelease(lightsData);
    }

    void Renderer::renderFrame(std::shared_ptr<FrameBuffer> fb,
                               int flags,
                               bool verifyCommit)
    {
      RenderContext ctx;
      if (verifyCommit) {
        Node::traverse(VerifyNodes{});
        traverse(ctx, "commit");
      }
      traverse(ctx, "render");
      variance = ospRenderFrame(fb->valueAs<OSPFrameBuffer>(),
                                ospRenderer,
                                flags);
    }

    std::string Renderer::toString() const
    {
      return "ospray::sg::Renderer";
    }

    void Renderer::traverse(RenderContext &ctx, const std::string& operation)
    {
      if (operation == "render") {
        preRender(ctx);
        postRender(ctx);
      }
      else
        Node::traverse(ctx,operation);
    }

    void Renderer::traverse(const std::string& operation)
    {
      Node::traverse(operation);
    }

    void Renderer::preRender(RenderContext& ctx)
    {
      ctx.ospRenderer = ospRenderer;
      ctx.ospRendererType = child("rendererType").valueAs<std::string>();
    }

    void Renderer::preCommit(RenderContext &ctx)
    {
      if (child("camera").hasChild("aspect") &&
          child("frameBuffer")["size"].lastModified() >
          child("camera")["aspect"].lastCommitted()) {

        auto fbSize = child("frameBuffer")["size"].valueAs<vec2i>();
        child("camera")["aspect"] = fbSize.x / float(fbSize.y);
      }
      auto rendererType = child("rendererType").valueAs<std::string>();
      if (!ospRenderer || rendererType != createdType) {
        auto setRenderer = [&](OSPRenderer handle, const std::string &rType) {
          Node::traverse(MarkAllAsModified{});
          ospRenderer = handle;
          createdType = rType;
          ospCommit(ospRenderer);
          setValue(ospRenderer);
        };

        auto potentialRenderer = ospNewRenderer(rendererType.c_str());
        if (potentialRenderer != nullptr) {
          setRenderer(potentialRenderer, rendererType);
        } else if (ospRenderer == nullptr) {
          //NOTE(jda) - default to scivs!
          setRenderer(ospNewRenderer("scivis"), "scivis");
          child("rendererType").setValue(std::string("scivis"));
        } else {
          //NOTE(jda) - revert rendererType back to name of currently valid
          //            renderer
          child("rendererType").setValue(createdType);
        }
      }

      auto backplate = child("backplate").nodeAs<Texture2D>();
      vec3f bgColor = child("bgColor").valueAs<vec3f>();
      memcpy(backplate->data, &bgColor.x, backplate->channels*backplate->depth);
      backplate->markAsModified();

      ctx.ospRenderer = ospRenderer;
      ctx.ospRendererType = rendererType;
      ctx.world = child("world").nodeAs<sg::Model>();
    }

    void Renderer::postCommit(RenderContext &ctx)
    {
      bool modified = lastModified() > frameMTime;
      if (!modified) {
        for (const auto& c : children()) {
          // ignore changes to the frame buffer/tone mapper
          if (c.second->lastModified() > frameMTime
              || (c.second->childrenLastModified() > frameMTime
              && c.first != "frameBuffer"))
          {
            modified = true;
            break;
          }
        }
      }

      if (modified) {
        ospFrameBufferClear(
          (OSPFrameBuffer)child("frameBuffer").valueAs<OSPObject>(),
          OSP_FB_COLOR | OSP_FB_ACCUM
        );

        if (lightsData == nullptr ||
          lightsBuildTime < child("lights").childrenLastModified())
        {
          // create and setup light list
          std::vector<OSPLight> lights;
          for(auto &lightNode : child("lights").children())
          {
            auto light = lightNode.second->valueAs<OSPLight>();
            if (light)
              lights.push_back(light);
          }

          if (lightsData)
            ospRelease(lightsData);
          lightsData = ospNewData(lights.size(), OSP_LIGHT, &lights[0]);
          ospCommit(lightsData);
          lightsBuildTime.renew();
        }

        // complete setup of renderer
        ospSetObject(ospRenderer,"camera", child("camera").valueAs<OSPObject>());
        ospSetObject(ospRenderer, "lights", lightsData);
        ospSetObject(ospRenderer, "backplate", child("backplate").valueAs<OSPObject>());

        if (child("world").childrenLastModified() > frameMTime)
        {
          child("world").finalize(ctx);
          ospSetObject(ospRenderer, "model",  child("world").valueAs<OSPObject>());
          if (child("autoEpsilon").valueAs<bool>()) {
            const box3f bounds = child("world")["bounds"].valueAs<box3f>();
            const float diam = length(bounds.size());
            float logDiam = ospcommon::log(diam);
            if (logDiam < 0.f)
            {
              logDiam = -1.f/logDiam;
            }
            const float epsilon = 1e-5f*logDiam;
            ospSet1f(ospRenderer, "epsilon", epsilon);
            ospSet1f(ospRenderer, "aoDistance", diam*0.3);
          }

        }

        if (!child("useBackplate").valueAs<bool>())
          ospSetObject(ospRenderer, "backplate", nullptr);

        ospCommit(ospRenderer);
        frameMTime.renew();
      }

    }

    OSPPickResult Renderer::pick(const vec2f &pickPos)
    {
      OSPPickResult result;
      ospPick(&result, ospRenderer, (const osp::vec2f&)pickPos);
      return result;
    }

    float Renderer::getLastVariance() const
    {
      return variance;
    }

    OSP_REGISTER_SG_NODE(Renderer);

  } // ::ospray::sg
} // ::ospray
<commit_msg>working, w/o cross-instance<commit_after>// ======================================================================== //
// Copyright 2009-2018 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "Renderer.h"

#include "common/FrameBuffer.h"
#include "visitor/MarkAllAsModified.h"
#include "visitor/VerifyNodes.h"

namespace ospray {
  namespace sg {

    static std::vector<std::string> globalWhiteList = {
      std::string("scivis"),
      std::string("pathtracer"),
      std::string("ao"),
      std::string("raycast"),
      std::string("raycast_vertexColor"),
      std::string("raycast_dPds"),
      std::string("raycast_dPdt"),
      std::string("raycast_Ng"),
      std::string("raycast_Ns"),
      std::string("backfacing_Ng"),
      std::string("backfacing_Ns"),
      std::string("primID"),
      std::string("geomID"),
      std::string("instID"),
      std::string("testFrame")
    };

    std::vector<std::string> Renderer::globalRendererTypeWhiteList()
    {
      return globalWhiteList;
    }

    void Renderer::setGlobalRendererTypeWhiteList(std::vector<std::string> list)
    {
      globalWhiteList = list;
    }

    Renderer::Renderer()
    {
      std::string defaultRendererType =
          globalWhiteList.empty() ? "scivis" : globalWhiteList[0];

      createChild("rendererType", "string", defaultRendererType,
                  NodeFlags::required |
                  NodeFlags::gui_combo,
                  "scivis: standard whitted style ray tracer. "
                  "pathtracer/pt: photo-realistic path tracer");

      std::vector<Any> whiteList;
      for (auto &v : globalWhiteList)
        whiteList.push_back(v);

      child("rendererType").setWhiteList(whiteList);
      createChild("world",
                  "Model").setDocumentation("model containing scene objects");
      createChild("camera", "PerspectiveCamera");
      createChild("frameBuffer", "FrameBuffer");
      createChild("lights");

      createChild("bgColor", "vec3f", vec3f(0.85f, 0.85f, 0.85f),
      // createChild("bgColor", "vec3f", vec3f(0.15f, 0.15f, 0.15f),
                  NodeFlags::required |
                  NodeFlags::gui_color);

      createChild("spp", "int", 1,
                  NodeFlags::required | NodeFlags::gui_slider,
                  "the number of samples rendered per pixel. The higher "
                  "the number, the smoother the resulting image.");
      child("spp").setMinMax(-8,128);

      createChild("minContribution", "float", 0.001f,
                  NodeFlags::required |
                  NodeFlags::gui_slider,
                  "sample contributions below this value will be neglected"
                  " to speed-up rendering.");
      child("minContribution").setMinMax(0.f, 0.1f);

      createChild("maxContribution", "float", 5.f,
                  NodeFlags::required |
                  NodeFlags::gui_slider,
                  "sample contributions above this value will be ignored."
                  "  This reduces bright dots appearing in images");
      child("maxContribution").setMinMax(1e-5f, 1e5f);

      createChild("varianceThreshold", "float", 0.f,
                  NodeFlags::required |
                  NodeFlags::gui_slider,
                  "the percent (%) threshold of pixel difference to enable"
                  " tile rendering early termination.");
      child("varianceThreshold").setMinMax(0.f, 25.f);

      //TODO: move these to seperate SciVisRenderer
      createChild("shadowsEnabled", "bool", true);
      createChild("maxDepth", "int", 5,
                  NodeFlags::required | NodeFlags::valid_min_max,
                  "maximum number of ray bounces").setMinMax(0,999);
      createChild("aoSamples", "int", 1,
                  NodeFlags::required |
                  NodeFlags::gui_slider,
                  "AO samples per frame.").setMinMax(0,128);

      createChild("aoDistance", "float", 10000.f,
                  NodeFlags::required,
                  "maximum distance ao rays will trace to."
                  " Useful if you do not want a large interior of a"
                  " building to be completely black from occlusion.");
      child("aoDistance").setMinMax(1e-20f, 1e20f);

      createChild("epsilon", "float", 1e-3f,
                  NodeFlags::required | NodeFlags::valid_min_max,
                  "epsilon step for secondary ray generation.  Adjust"
                  " if you see speckles or a lack of lighting.");
      child("epsilon").setMinMax(1e-20f, 1e20f);
      createChild("autoEpsilon", "bool", true, NodeFlags::required,
        "automatically adjust epsilon step");

      createChild("oneSidedLighting", "bool", true, NodeFlags::required);
      createChild("aoTransparencyEnabled", "bool", true, NodeFlags::required);

      createChild("backplate", "Texture2D");
      auto backplate = child("backplate").nodeAs<Texture2D>();
      backplate->size.x = 1;
      backplate->size.y = 1;
      backplate->channels = 3;
      backplate->preferLinear = true;
      backplate->depth = 4;
      const size_t stride = backplate->size.x * backplate->channels * backplate->depth;
      backplate->data = malloc(sizeof(unsigned char) * backplate->size.y * stride);
      vec3f bgColor = child("bgColor").valueAs<vec3f>();
      memcpy(backplate->data, &bgColor.x, backplate->channels*backplate->depth);
      createChild("useBackplate", "bool", true, NodeFlags::none, "use\
           backplate for path tracer");
    }

    Renderer::~Renderer()
    {
      if (lightsData)
        ospRelease(lightsData);
    }

    void Renderer::renderFrame(std::shared_ptr<FrameBuffer> fb,
                               int flags,
                               bool verifyCommit)
    {
      RenderContext ctx;
      if (verifyCommit) {
        Node::traverse(VerifyNodes{});
        traverse(ctx, "commit");
      }
      traverse(ctx, "render");
      variance = ospRenderFrame(fb->valueAs<OSPFrameBuffer>(),
                                ospRenderer,
                                flags);
    }

    std::string Renderer::toString() const
    {
      return "ospray::sg::Renderer";
    }

    void Renderer::traverse(RenderContext &ctx, const std::string& operation)
    {
      if (operation == "render") {
        preRender(ctx);
        postRender(ctx);
      }
      else
        Node::traverse(ctx,operation);
    }

    void Renderer::traverse(const std::string& operation)
    {
      Node::traverse(operation);
    }

    void Renderer::preRender(RenderContext& ctx)
    {
      ctx.ospRenderer = ospRenderer;
      ctx.ospRendererType = child("rendererType").valueAs<std::string>();
    }

    void Renderer::preCommit(RenderContext &ctx)
    {
      if (child("camera").hasChild("aspect") &&
          child("frameBuffer")["size"].lastModified() >
          child("camera")["aspect"].lastCommitted()) {

        auto fbSize = child("frameBuffer")["size"].valueAs<vec2i>();
        child("camera")["aspect"] = fbSize.x / float(fbSize.y);
      }
      auto rendererType = child("rendererType").valueAs<std::string>();
      if (!ospRenderer || rendererType != createdType) {
        auto setRenderer = [&](OSPRenderer handle, const std::string &rType) {
          Node::traverse(MarkAllAsModified{});
          ospRenderer = handle;
          createdType = rType;
          ospCommit(ospRenderer);
          setValue(ospRenderer);
        };

        auto potentialRenderer = ospNewRenderer(rendererType.c_str());
        if (potentialRenderer != nullptr) {
          setRenderer(potentialRenderer, rendererType);
        } else if (ospRenderer == nullptr) {
          //NOTE(jda) - default to scivs!
          setRenderer(ospNewRenderer("scivis"), "scivis");
          child("rendererType").setValue(std::string("scivis"));
        } else {
          //NOTE(jda) - revert rendererType back to name of currently valid
          //            renderer
          child("rendererType").setValue(createdType);
        }
      }

      auto backplate = child("backplate").nodeAs<Texture2D>();
      vec3f bgColor = child("bgColor").valueAs<vec3f>();
      memcpy(backplate->data, &bgColor.x, backplate->channels*backplate->depth);
      backplate->markAsModified();

      ctx.ospRenderer = ospRenderer;
      ctx.ospRendererType = rendererType;
      ctx.world = child("world").nodeAs<sg::Model>();
    }

    void Renderer::postCommit(RenderContext &ctx)
    {
      bool modified = lastModified() > frameMTime;
      if (!modified) {
        for (const auto& c : children()) {
          // ignore changes to the frame buffer/tone mapper
          if (c.second->lastModified() > frameMTime
              || (c.second->childrenLastModified() > frameMTime
              && c.first != "frameBuffer"))
          {
            modified = true;
            break;
          }
        }
      }

      if (modified) {
        ospFrameBufferClear(
          (OSPFrameBuffer)child("frameBuffer").valueAs<OSPObject>(),
          OSP_FB_COLOR | OSP_FB_ACCUM
        );

        if (lightsData == nullptr ||
          lightsBuildTime < child("lights").childrenLastModified())
        {
          // create and setup light list
          std::vector<OSPLight> lights;
          for(auto &lightNode : child("lights").children())
          {
            auto light = lightNode.second->valueAs<OSPLight>();
            if (light)
              lights.push_back(light);
          }

          if (lightsData)
            ospRelease(lightsData);
          lightsData = ospNewData(lights.size(), OSP_LIGHT, &lights[0]);
          ospCommit(lightsData);
          lightsBuildTime.renew();
        }

        // complete setup of renderer
        ospSetObject(ospRenderer,"camera", child("camera").valueAs<OSPObject>());
        ospSetObject(ospRenderer, "lights", lightsData);
        ospSetObject(ospRenderer, "backplate", child("backplate").valueAs<OSPObject>());

        if (child("world").childrenLastModified() > frameMTime)
        {
          child("world").finalize(ctx);
          ospSetObject(ospRenderer, "model",  child("world").valueAs<OSPObject>());
          if (child("autoEpsilon").valueAs<bool>()) {
            const box3f bounds = child("world")["bounds"].valueAs<box3f>();
            const float diam = length(bounds.size());
            float logDiam = ospcommon::log(diam);
            if (logDiam < 0.f)
            {
              logDiam = -1.f/logDiam;
            }
            const float epsilon = 1e-5f*logDiam;
            ospSet1f(ospRenderer, "epsilon", epsilon);
            ospSet1f(ospRenderer, "aoDistance", diam*0.3);
          }

        }

        if (!child("useBackplate").valueAs<bool>())
          ospSetObject(ospRenderer, "backplate", nullptr);

        ospCommit(ospRenderer);
        frameMTime.renew();
      }

    }

    OSPPickResult Renderer::pick(const vec2f &pickPos)
    {
      OSPPickResult result;
      ospPick(&result, ospRenderer, (const osp::vec2f&)pickPos);
      return result;
    }

    float Renderer::getLastVariance() const
    {
      return variance;
    }

    OSP_REGISTER_SG_NODE(Renderer);

  } // ::ospray::sg
} // ::ospray
<|endoftext|>


<commit_before>#include <iostream>
#include "Includes/EngineLogger.h"
#include "SFML/Graphics.hpp"

int main() {
	sf::RectangleShape rect(sf::Vector2f(50,40));

	sf::RenderWindow window(sf::VideoMode(1280, 720), "Test");
	EngineLogger logger = EngineLogger();
	logger.Log(EngineLogger::LogLevel::LOG_INFO, "Renderer successfully initialised.");
	while (window.isOpen()) {
		sf::Event event;
		while (window.pollEvent(event)) {
			switch (event.type) {
			case sf::Event::Closed:
				window.close();
				break;
			default:
				break;
			}
		}

		window.clear(sf::Color::Black);
		window.draw(rect);
		window.display();

	}
}<commit_msg>made spacing less ugly<commit_after>#include <iostream>
#include "Includes/EngineLogger.h"
#include "SFML/Graphics.hpp"

int main() {
	sf::RectangleShape rect(sf::Vector2f(50,40));

	sf::RenderWindow window(sf::VideoMode(1280, 720), "Test");

	EngineLogger logger = EngineLogger();
	logger.Log(EngineLogger::LogLevel::LOG_INFO, "Renderer successfully initialised.");

	while (window.isOpen()) {
		sf::Event event;
		while (window.pollEvent(event)) {
			switch (event.type) {
			case sf::Event::Closed:
				window.close();
				break;
			default:
				break;
			}
		}

		window.clear(sf::Color::Black);
		window.draw(rect);
		window.display();

	}
}<|endoftext|>


<commit_before>/*
 *  Copyright 2010-2012 Fabric Engine Inc. All rights reserved.
 */

#include "Inst.h"

#include <Fabric/Core/KL/StringSource.h>
#include <Fabric/Core/KL/Scanner.h>
#include <Fabric/Core/KL/Parser.hpp>
#include <Fabric/Core/AST/Function.h>
#include <Fabric/Core/AST/GlobalList.h>
#include <Fabric/Core/CG/Manager.h>
#include <Fabric/Core/CG/ModuleBuilder.h>
#include <Fabric/Core/RT/Impl.h>
#include <Fabric/Core/DG/Context.h>
#include <Fabric/Core/IO/Helpers.h>
#include <Fabric/Core/IO/Dir.h>
#include <Fabric/Core/Plug/Helpers.h>
#include <Fabric/Core/Build.h>
#include <Fabric/EDK/Common.h>

namespace Fabric
{
  namespace Plug
  {

    //typedef void (*OnLoadFn)( SDK::Value FABRIC );
    //typedef void (*OnUnloadFn)( SDK::Value FABRIC );

    RC::Handle<Inst> Inst::Create(
      RC::ConstHandle<IO::Dir> const &extensionDir,
      std::string const &extensionName,
      std::string const &jsonDesc,
      std::vector<std::string> const &pluginDirs,
      RC::Handle<CG::Manager> const &cgManager,
      EDK::Callbacks const &callbacks,
      std::map< std::string, void (*)( void * ) > &implNameToDestructorMap
      )
    {
      return new Inst( extensionDir, extensionName, jsonDesc, pluginDirs, cgManager, callbacks, implNameToDestructorMap );
    }

    Inst::Inst(
      RC::ConstHandle<IO::Dir> const &extensionDir,
      std::string const &extensionName,
      std::string const &jsonDesc,
      std::vector<std::string> const &pluginDirs,
      RC::Handle<CG::Manager> const &cgManager,
      EDK::Callbacks const &callbacks,
      std::map< std::string, void (*)( void * ) > &implNameToDestructorMap
      )
      : m_name( extensionName )
      , m_jsonDesc( jsonDesc )
    {
      try
      {
        JSON::Decoder jsonDecode( jsonDesc.data(), jsonDesc.length() );
        JSON::Entity jsonEntity;
        if ( !jsonDecode.getNext( jsonEntity ) )
          throw Exception( "missing JSON entity" );
        jsonEntity.requireObject();
        m_desc = parseDesc( jsonEntity );
        if ( jsonDecode.getNext( jsonEntity ) )
          throw Exception( "extra JSON entity" );
      }
      catch ( Exception e )
      {
        throw "JSON description: " + e;
      }

      /*
      m_fabricLIBObject = LIB::NakedObject::Create();
      m_fabricLIBObject->set( "hostTriple", LIB::ReferencedString::Create( Util::getHostTriple() ) );
      m_fabricLIBObject->set( "DependencyGraph", LIBDG::Namespace::Create( dgContext ) );
      */
      std::vector< std::string > libs;
      m_desc.libs.appendMatching( Util::getHostTriple(), libs );
      std::string libSuffix = "-" + std::string(buildOS) + "-" + std::string(buildArch);

      for ( size_t i=0; i<libs.size(); ++i )
      {
        std::string resolvedName;
        SOLibHandle soLibHandle = SOLibOpen( libs[i]+libSuffix, resolvedName, false, pluginDirs );
        m_resolvedNameToSOLibHandleMap.insert( ResolvedNameToSOLibHandleMap::value_type( resolvedName, soLibHandle ) );
        m_orderedSOLibHandles.push_back( soLibHandle );
      }

      void *resolvedFabricEDKInitFunction = 0;
      for ( size_t i=0; i<m_orderedSOLibHandles.size(); ++i )
      {
        resolvedFabricEDKInitFunction = SOLibResolve( m_orderedSOLibHandles[i], "FabricEDKInit" );
        if ( resolvedFabricEDKInitFunction )
          break;
      }
      if ( !resolvedFabricEDKInitFunction )
        throw Exception( "error: extension doesn't implement function FabricEDKInit through macro IMPLEMENT_FABRIC_EDK_ENTRIES" );

      ( *( FabricEDKInitPtr )resolvedFabricEDKInitFunction )( callbacks );

      for ( size_t i=0; i<m_orderedSOLibHandles.size(); ++i )
      {
        /*
        OnLoadFn onLoadFn = (OnLoadFn)SOLibResolve( m_orderedSOLibHandles[i], "FabricOnLoad" );
        if ( onLoadFn )
          onLoadFn( SDK::Value::Bind( m_fabricLIBObject ) );
        */
      }

      /*
      for ( size_t i=0; i<m_desc.interface.methods.size(); ++i )
      {
        std::string const &methodName = m_desc.interface.methods[i];
        Method method = 0;
        for ( size_t j=0; j<m_orderedSOLibHandles.size(); ++j )
        {
          SOLibHandle soLibHandle = m_orderedSOLibHandles[j];
          method = (Method)SOLibResolve( soLibHandle, methodName );
          if ( method )
            break;
        }
        if ( !method )
          throw Exception( "method "+_(methodName)+" not found" );
        m_methodMap.insert( MethodMap::value_type( methodName, method ) );
      }
      */

      std::vector<std::string> codeFiles;
      m_desc.code.appendMatching( Util::getHostTriple(), codeFiles );
      std::string filename;
      m_code = "";
      for ( std::vector<std::string>::const_iterator it=codeFiles.begin(); it!=codeFiles.end(); ++it )
      {
        std::string const &codeEntry = *it;

        if ( filename.empty() )
          filename = codeEntry;

        std::string code;
        try
        {
          code = extensionDir->getFileContents( codeEntry );
        }
        catch ( Exception e )
        {
          throw _(codeEntry) + ": " + e;
        }
        m_code += code + "\n";
      }

      RC::ConstHandle<KL::Source> source = KL::StringSource::Create( filename, m_code );
      RC::Handle<KL::Scanner> scanner = KL::Scanner::Create( source );
      m_ast = KL::Parse( scanner, m_diagnostics );
      if ( !m_diagnostics.containsError() )
        m_ast->registerTypes( cgManager, m_diagnostics );
      for ( CG::Diagnostics::const_iterator it=m_diagnostics.begin(); it!=m_diagnostics.end(); ++it )
      {
        CG::Location const &location = it->first;
        CG::Diagnostic const &diagnostic = it->second;
        FABRIC_LOG( "[%s] %s:%u:%u: %s: %s", extensionName.c_str(), location.getFilename()->c_str(), (unsigned)location.getLine(), (unsigned)location.getColumn(), diagnostic.getLevelDesc(), diagnostic.getDesc().c_str() );
      }
      if ( m_diagnostics.containsError() )
        throw Exception( "KL compile failed" );

      std::vector< RC::ConstHandle<AST::FunctionBase> > functionBases;
      m_ast->collectFunctionBases( functionBases );
      for ( std::vector< RC::ConstHandle<AST::FunctionBase> >::const_iterator it=functionBases.begin(); it!=functionBases.end(); ++it )
      {
        RC::ConstHandle<AST::FunctionBase> const &functionBase = *it;

        if ( !functionBase->getBody() )
        {
          std::string symbolName = functionBase->getSymbolName( cgManager );
          void *resolvedFunction = 0;
          for ( size_t i=0; i<m_orderedSOLibHandles.size(); ++i )
          {
            resolvedFunction = SOLibResolve( m_orderedSOLibHandles[i], symbolName );
            if ( resolvedFunction )
              break;
          }
          if ( !resolvedFunction )
            throw Exception( "error: symbol " + _(symbolName) + ", prototyped in KL, not found in native code" );
          m_externalFunctionMap.insert( ExternalFunctionMap::value_type( symbolName, resolvedFunction ) );

          if ( functionBase->isDestructor() )
          {
            RC::ConstHandle<AST::Destructor> destructor = RC::ConstHandle<AST::Destructor>::StaticCast( functionBase );
            std::string thisTypeName = destructor->getThisTypeName();
            implNameToDestructorMap[thisTypeName] = (void (*)( void * )) resolvedFunction;
          }
        }
      }

      m_jsConstants = m_desc.jsConstants.concatMatching( Util::getHostTriple() );
    }

    Inst::~Inst()
    {
      for ( size_t i=m_orderedSOLibHandles.size(); i--; )
      {
        /*
        OnUnloadFn onUnloadFn = (OnUnloadFn)SOLibResolve( m_orderedSOLibHandles[i], "FabricOnUnload" );
        if ( onUnloadFn )
          onUnloadFn( SDK::Value::Bind( m_fabricLIBObject ) );
        */
      }

      for ( ResolvedNameToSOLibHandleMap::const_iterator it=m_resolvedNameToSOLibHandleMap.begin(); it !=m_resolvedNameToSOLibHandleMap.end(); ++it )
      {
        SOLibClose( it->second, it->first );
      }
    }

    void *Inst::llvmResolveExternalFunction( std::string const &name ) const
    {
      void *result = 0;
      ExternalFunctionMap::const_iterator it = m_externalFunctionMap.find( name );
      if ( it != m_externalFunctionMap.end() )
        result = it->second;
      return result;
    }

    bool Inst::hasMethod( std::string const &methodName ) const
    {
      /*
      MethodMap::const_iterator it = m_methodMap.find( methodName );
      return it != m_methodMap.end();
      */
      return false;
    }

    void Inst::enumerateMethods( std::vector<std::string> &result ) const
    {
      /*
      for ( MethodMap::const_iterator it=m_methodMap.begin(); it!=m_methodMap.end(); ++it )
        result.push_back( it->first );
      */
    }

      /*
    RC::Handle<LIB::Value> Inst::invokeMethod( std::string const &methodName, std::vector< RC::Handle<LIB::Value> > const &args )
    {
      MethodMap::const_iterator it = m_methodMap.find( methodName );
      FABRIC_ASSERT( it != m_methodMap.end() );
      return SDK::Value::Unbind( it->second( SDK::Value::Bind( m_fabricLIBObject ), SDK::Value::LIBArgsToSDKArgs( args ) ) );
    }
      */

    void Inst::jsonDesc( JSON::Encoder &resultEncoder ) const
    {
      JSON::ObjectEncoder resultObjectEncoder = resultEncoder.makeObject();
      {
        JSON::Encoder memberEncoder = resultObjectEncoder.makeMember( "code", 4 );
        memberEncoder.makeString( m_code );
      }
      {
        JSON::Encoder memberEncoder = resultObjectEncoder.makeMember( "jsConstants", 11 );
        memberEncoder.makeString( m_jsConstants );
      }
    }

    RC::ConstHandle<AST::GlobalList> Inst::getAST() const
    {
      return m_ast;
    }
  };
};
<commit_msg>Add support for KL-only extensions<commit_after>/*
 *  Copyright 2010-2012 Fabric Engine Inc. All rights reserved.
 */

#include "Inst.h"

#include <Fabric/Core/KL/StringSource.h>
#include <Fabric/Core/KL/Scanner.h>
#include <Fabric/Core/KL/Parser.hpp>
#include <Fabric/Core/AST/Function.h>
#include <Fabric/Core/AST/GlobalList.h>
#include <Fabric/Core/CG/Manager.h>
#include <Fabric/Core/CG/ModuleBuilder.h>
#include <Fabric/Core/RT/Impl.h>
#include <Fabric/Core/DG/Context.h>
#include <Fabric/Core/IO/Helpers.h>
#include <Fabric/Core/IO/Dir.h>
#include <Fabric/Core/Plug/Helpers.h>
#include <Fabric/Core/Build.h>
#include <Fabric/EDK/Common.h>

namespace Fabric
{
  namespace Plug
  {

    //typedef void (*OnLoadFn)( SDK::Value FABRIC );
    //typedef void (*OnUnloadFn)( SDK::Value FABRIC );

    RC::Handle<Inst> Inst::Create(
      RC::ConstHandle<IO::Dir> const &extensionDir,
      std::string const &extensionName,
      std::string const &jsonDesc,
      std::vector<std::string> const &pluginDirs,
      RC::Handle<CG::Manager> const &cgManager,
      EDK::Callbacks const &callbacks,
      std::map< std::string, void (*)( void * ) > &implNameToDestructorMap
      )
    {
      return new Inst( extensionDir, extensionName, jsonDesc, pluginDirs, cgManager, callbacks, implNameToDestructorMap );
    }

    Inst::Inst(
      RC::ConstHandle<IO::Dir> const &extensionDir,
      std::string const &extensionName,
      std::string const &jsonDesc,
      std::vector<std::string> const &pluginDirs,
      RC::Handle<CG::Manager> const &cgManager,
      EDK::Callbacks const &callbacks,
      std::map< std::string, void (*)( void * ) > &implNameToDestructorMap
      )
      : m_name( extensionName )
      , m_jsonDesc( jsonDesc )
    {
      try
      {
        JSON::Decoder jsonDecode( jsonDesc.data(), jsonDesc.length() );
        JSON::Entity jsonEntity;
        if ( !jsonDecode.getNext( jsonEntity ) )
          throw Exception( "missing JSON entity" );
        jsonEntity.requireObject();
        m_desc = parseDesc( jsonEntity );
        if ( jsonDecode.getNext( jsonEntity ) )
          throw Exception( "extra JSON entity" );
      }
      catch ( Exception e )
      {
        throw "JSON description: " + e;
      }

      /*
      m_fabricLIBObject = LIB::NakedObject::Create();
      m_fabricLIBObject->set( "hostTriple", LIB::ReferencedString::Create( Util::getHostTriple() ) );
      m_fabricLIBObject->set( "DependencyGraph", LIBDG::Namespace::Create( dgContext ) );
      */
      std::vector< std::string > libs;
      m_desc.libs.appendMatching( Util::getHostTriple(), libs );
      std::string libSuffix = "-" + std::string(buildOS) + "-" + std::string(buildArch);

      for ( size_t i=0; i<libs.size(); ++i )
      {
        std::string resolvedName;
        SOLibHandle soLibHandle = SOLibOpen( libs[i]+libSuffix, resolvedName, false, pluginDirs );
        m_resolvedNameToSOLibHandleMap.insert( ResolvedNameToSOLibHandleMap::value_type( resolvedName, soLibHandle ) );
        m_orderedSOLibHandles.push_back( soLibHandle );
      }

      if ( !m_orderedSOLibHandles.empty() )
      {
        void *resolvedFabricEDKInitFunction = 0;
        for ( size_t i=0; i<m_orderedSOLibHandles.size(); ++i )
        {
          resolvedFabricEDKInitFunction = SOLibResolve( m_orderedSOLibHandles[i], "FabricEDKInit" );
          if ( resolvedFabricEDKInitFunction )
            break;
        }
        if ( !resolvedFabricEDKInitFunction )
          throw Exception( "error: extension doesn't implement function FabricEDKInit through macro IMPLEMENT_FABRIC_EDK_ENTRIES" );

        ( *( FabricEDKInitPtr )resolvedFabricEDKInitFunction )( callbacks );
      }

      for ( size_t i=0; i<m_orderedSOLibHandles.size(); ++i )
      {
        /*
        OnLoadFn onLoadFn = (OnLoadFn)SOLibResolve( m_orderedSOLibHandles[i], "FabricOnLoad" );
        if ( onLoadFn )
          onLoadFn( SDK::Value::Bind( m_fabricLIBObject ) );
        */
      }

      /*
      for ( size_t i=0; i<m_desc.interface.methods.size(); ++i )
      {
        std::string const &methodName = m_desc.interface.methods[i];
        Method method = 0;
        for ( size_t j=0; j<m_orderedSOLibHandles.size(); ++j )
        {
          SOLibHandle soLibHandle = m_orderedSOLibHandles[j];
          method = (Method)SOLibResolve( soLibHandle, methodName );
          if ( method )
            break;
        }
        if ( !method )
          throw Exception( "method "+_(methodName)+" not found" );
        m_methodMap.insert( MethodMap::value_type( methodName, method ) );
      }
      */

      std::vector<std::string> codeFiles;
      m_desc.code.appendMatching( Util::getHostTriple(), codeFiles );
      std::string filename;
      m_code = "";
      for ( std::vector<std::string>::const_iterator it=codeFiles.begin(); it!=codeFiles.end(); ++it )
      {
        std::string const &codeEntry = *it;

        if ( filename.empty() )
          filename = codeEntry;

        std::string code;
        try
        {
          code = extensionDir->getFileContents( codeEntry );
        }
        catch ( Exception e )
        {
          throw _(codeEntry) + ": " + e;
        }
        m_code += code + "\n";
      }

      RC::ConstHandle<KL::Source> source = KL::StringSource::Create( filename, m_code );
      RC::Handle<KL::Scanner> scanner = KL::Scanner::Create( source );
      m_ast = KL::Parse( scanner, m_diagnostics );
      if ( !m_diagnostics.containsError() )
        m_ast->registerTypes( cgManager, m_diagnostics );
      for ( CG::Diagnostics::const_iterator it=m_diagnostics.begin(); it!=m_diagnostics.end(); ++it )
      {
        CG::Location const &location = it->first;
        CG::Diagnostic const &diagnostic = it->second;
        FABRIC_LOG( "[%s] %s:%u:%u: %s: %s", extensionName.c_str(), location.getFilename()->c_str(), (unsigned)location.getLine(), (unsigned)location.getColumn(), diagnostic.getLevelDesc(), diagnostic.getDesc().c_str() );
      }
      if ( m_diagnostics.containsError() )
        throw Exception( "KL compile failed" );

      std::vector< RC::ConstHandle<AST::FunctionBase> > functionBases;
      m_ast->collectFunctionBases( functionBases );
      for ( std::vector< RC::ConstHandle<AST::FunctionBase> >::const_iterator it=functionBases.begin(); it!=functionBases.end(); ++it )
      {
        RC::ConstHandle<AST::FunctionBase> const &functionBase = *it;

        if ( !functionBase->getBody() )
        {
          std::string symbolName = functionBase->getSymbolName( cgManager );
          void *resolvedFunction = 0;
          for ( size_t i=0; i<m_orderedSOLibHandles.size(); ++i )
          {
            resolvedFunction = SOLibResolve( m_orderedSOLibHandles[i], symbolName );
            if ( resolvedFunction )
              break;
          }
          if ( !resolvedFunction )
            throw Exception( "error: symbol " + _(symbolName) + ", prototyped in KL, not found in native code" );
          m_externalFunctionMap.insert( ExternalFunctionMap::value_type( symbolName, resolvedFunction ) );

          if ( functionBase->isDestructor() )
          {
            RC::ConstHandle<AST::Destructor> destructor = RC::ConstHandle<AST::Destructor>::StaticCast( functionBase );
            std::string thisTypeName = destructor->getThisTypeName();
            implNameToDestructorMap[thisTypeName] = (void (*)( void * )) resolvedFunction;
          }
        }
      }

      m_jsConstants = m_desc.jsConstants.concatMatching( Util::getHostTriple() );
    }

    Inst::~Inst()
    {
      for ( size_t i=m_orderedSOLibHandles.size(); i--; )
      {
        /*
        OnUnloadFn onUnloadFn = (OnUnloadFn)SOLibResolve( m_orderedSOLibHandles[i], "FabricOnUnload" );
        if ( onUnloadFn )
          onUnloadFn( SDK::Value::Bind( m_fabricLIBObject ) );
        */
      }

      for ( ResolvedNameToSOLibHandleMap::const_iterator it=m_resolvedNameToSOLibHandleMap.begin(); it !=m_resolvedNameToSOLibHandleMap.end(); ++it )
      {
        SOLibClose( it->second, it->first );
      }
    }

    void *Inst::llvmResolveExternalFunction( std::string const &name ) const
    {
      void *result = 0;
      ExternalFunctionMap::const_iterator it = m_externalFunctionMap.find( name );
      if ( it != m_externalFunctionMap.end() )
        result = it->second;
      return result;
    }

    bool Inst::hasMethod( std::string const &methodName ) const
    {
      /*
      MethodMap::const_iterator it = m_methodMap.find( methodName );
      return it != m_methodMap.end();
      */
      return false;
    }

    void Inst::enumerateMethods( std::vector<std::string> &result ) const
    {
      /*
      for ( MethodMap::const_iterator it=m_methodMap.begin(); it!=m_methodMap.end(); ++it )
        result.push_back( it->first );
      */
    }

      /*
    RC::Handle<LIB::Value> Inst::invokeMethod( std::string const &methodName, std::vector< RC::Handle<LIB::Value> > const &args )
    {
      MethodMap::const_iterator it = m_methodMap.find( methodName );
      FABRIC_ASSERT( it != m_methodMap.end() );
      return SDK::Value::Unbind( it->second( SDK::Value::Bind( m_fabricLIBObject ), SDK::Value::LIBArgsToSDKArgs( args ) ) );
    }
      */

    void Inst::jsonDesc( JSON::Encoder &resultEncoder ) const
    {
      JSON::ObjectEncoder resultObjectEncoder = resultEncoder.makeObject();
      {
        JSON::Encoder memberEncoder = resultObjectEncoder.makeMember( "code", 4 );
        memberEncoder.makeString( m_code );
      }
      {
        JSON::Encoder memberEncoder = resultObjectEncoder.makeMember( "jsConstants", 11 );
        memberEncoder.makeString( m_jsConstants );
      }
    }

    RC::ConstHandle<AST::GlobalList> Inst::getAST() const
    {
      return m_ast;
    }
  };
};
<|endoftext|>


<commit_before>AliJetReader *CreateJetReader(Char_t *jr); // Common config
AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius = -1);

AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf,Float_t radius = -1); // for the new AF

AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf, Float_t radius)
{
  // Creates a jet finder task, configures it and adds it to the analysis manager.

   // Get the pointer to the existing analysis manager via the static access method.
   //==============================================================================
   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
   if (!mgr) {
      ::Error("AddTaskJets", "No analysis manager to connect to.");
      return NULL;
   }

   // Check the analysis type using the event handlers connected to the analysis manager.
   //==============================================================================
   if (!mgr->GetInputEventHandler()) {
      ::Error("AddTaskJets", "This task requires an input event handler");
      return NULL;
   }

   // Create the task and configure it.
   //===========================================================================
   AliAnalysisTaskJets *jetana;
   AliJetReader *er = CreateJetReader(jr);
    // Define jet header and jet finder
   AliJetFinder *jetFinder = CreateJetFinder(jf,radius);

   if (jetFinder){
       if (er) jetFinder->SetJetReader(er);
   }

   char *cRadius = "";
   if(radius>0)cRadius = Form("%02d",(int)(radius*10));

   jetana = new AliAnalysisTaskJets(Form("JetAnalysis%s%s%s",jr,jf,cRadius));
   AliAnalysisDataContainer *cout_jet = mgr->CreateContainer(Form("jethist%s%s%s",jr,jf,cRadius), TList::Class(),
							     AliAnalysisManager::kOutputContainer, Form("jethist%s_%s%s.root",jr,jf,cRadius));
   // Connect jet finder to task.
   jetana->SetJetFinder(jetFinder);
   jetana->SetConfigFile("");
   jetana->SetDebugLevel(10);
   mgr->AddTask(jetana);

   // Create ONLY the output containers for the data produced by the task.
   // Get and connect other common input/output containers via the manager as below
   //==============================================================================
   mgr->ConnectInput  (jetana, 0, mgr->GetCommonInputContainer());
// AOD output slot will be used in a different way in future
   mgr->ConnectOutput (jetana, 0, mgr->GetCommonOutputContainer());
   mgr->ConnectOutput (jetana, 1, cout_jet);

   return jetana;
}

AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius){

  switch (jf) {
  case "CDF":
    AliCdfJetHeader *jh = new AliCdfJetHeader();
    jh->SetRadius(0.7);

    jetFinder = new AliCdfJetFinder();
    jetFinder->SetOutputFile("jets.root");
    if (jh) jetFinder->SetJetHeader(jh);
    break;

  case "DA":
    AliDAJetHeader *jh=new AliDAJetHeader();
    jh->SetComment("DA jet code with default parameters");
    jh->SelectJets(kTRUE);
    jh->SetNclust(10);

    jetFinder = new AliDAJetFinder();
    if (jh) jetFinder->SetJetHeader(jh);
    break;

  case "Fastjet":
    AliFastJetHeader *jh = new AliFastJetHeader();
    jh->SetRparam(0.7); // setup parameters

    jetFinder = new AliFastJetFinder();
    jetFinder->SetOutputFile("jets.root");
    if (jh) jetFinder->SetJetHeader(jh);
    break;

  case "UA1":
    AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1();
    jh->SetComment("UA1 jet code with default parameters");
    jh->BackgMode(0);
    jh->SetRadius(0.4);
    if(radius>0)jh->SetRadius(radius);
    jh->SetEtSeed(4.);
    jh->SetLegoNbinPhi(432);
    jh->SetLegoNbinEta(274);
    jh->SetLegoEtaMin(-2);
    jh->SetLegoEtaMax(+2);
    jh->SetMinJetEt(10.);
    jh->SetJetEtaMax(1.5);
    jh->SetJetEtaMin(-1.5);

    jetFinder = new AliUA1JetFinderV1();
    if (jh) jetFinder->SetJetHeader(jh);
    break;

  case "UA1MC":
    AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1();
    jh->SetComment("UA1 jet code with default MC parameters");
    jh->BackgMode(0);
    jh->SetRadius(1.0);
    if(radius>0)jh->SetRadius(radius);
    jh->SetEtSeed(4.);
    jh->SetLegoNbinPhi(432);
    jh->SetLegoNbinEta(274);
    jh->SetLegoEtaMin(-2);
    jh->SetLegoEtaMax(+2);
    jh->SetMinJetEt(10.);
    jh->SetJetEtaMax(1.5);
    jh->SetJetEtaMin(-1.5);

    jetFinder = new AliUA1JetFinderV1();
    if (jh) jetFinder->SetJetHeader(jh);
    break;
  case default:
    ::Error("AddTaskJets", "Wrong jet finder selected\n");
    return 0;
  }

  return jetFinder;

}

AliJetReader *CreateJetReader(Char_t *jr){
  AliJetReader *er = 0;

  switch (jr) {
  case "MC":
    AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader();
    jrh->SetComment("MC full Kinematics");
    jrh->SetFastSimTPC(kFALSE);
    jrh->SetFastSimEMCAL(kFALSE);
    jrh->SetPtCut(0.);
    jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9
    // Define reader and set its header
    er = new AliJetKineReader();
    er->SetReaderHeader(jrh);
    break;
  case "MC2":
    AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader();
    jrh->SetComment("MC full Kinematics spearate config");
    jrh->SetFastSimTPC(kFALSE);
    jrh->SetFastSimEMCAL(kFALSE);
    jrh->SetPtCut(0.);
    jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9
    // Define reader and set its header
    er = new AliJetKineReader();
    er->SetReaderHeader(jrh);
    break;
  case "ESD":
    AliJetESDReaderHeader *jrh = new AliJetESDReaderHeader();
    jrh->SetComment("Testing");
    jrh->SetFirstEvent(0);
    jrh->SetLastEvent(1000);
    jrh->SetPtCut(0.);
    jrh->SetReadSignalOnly(kFALSE);
    // Define reader and set its header
    er = new AliJetESDReader();
    er->SetReaderHeader(jrh);
    break;

  case "AOD":
    AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader();
    jrh->SetComment("AOD Reader");
    jrh->SetPtCut(0.);
    jrh->SetTestFilterMask(1<<0);
    // Define reader and set its header
    er = new AliJetAODReader();
    er->SetReaderHeader(jrh);
    break;

  default:
    ::Error("AddTaskJets", "Wrong jet reader selected\n");
    return 0;
  }

  return er;

}
<commit_msg>Create non standard branch in case AODs are read as input. (M. Gheata)<commit_after>AliJetReader *CreateJetReader(Char_t *jr); // Common config
AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius = -1);

AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf,Float_t radius = -1); // for the new AF

AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf, Float_t radius)
{
  // Creates a jet finder task, configures it and adds it to the analysis manager.

   // Get the pointer to the existing analysis manager via the static access method.
   //==============================================================================
   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
   if (!mgr) {
      ::Error("AddTaskJets", "No analysis manager to connect to.");
      return NULL;
   }

   // Check the analysis type using the event handlers connected to the analysis manager.
   //==============================================================================
   if (!mgr->GetInputEventHandler()) {
      ::Error("AddTaskJets", "This task requires an input event handler");
      return NULL;
   }

   // Create the task and configure it.
   //===========================================================================
   AliAnalysisTaskJets *jetana;
   AliJetReader *er = CreateJetReader(jr);
    // Define jet header and jet finder
   AliJetFinder *jetFinder = CreateJetFinder(jf,radius);

   if (jetFinder){
       if (er) jetFinder->SetJetReader(er);
   }

   char *cRadius = "";
   if(radius>0)cRadius = Form("%02d",(int)(radius*10));

   jetana = new AliAnalysisTaskJets(Form("JetAnalysis%s%s%s",jr,jf,cRadius));
   TString type = mgr->GetInputEventHandler()->GetDataType();
   if (type == "AOD") jetana->SetNonStdBranch(Form("jets%s",jf));

   AliAnalysisDataContainer *cout_jet = mgr->CreateContainer(Form("jethist%s%s%s",jr,jf,cRadius), TList::Class(),
							     AliAnalysisManager::kOutputContainer, Form("jethist%s_%s%s.root",jr,jf,cRadius));
   // Connect jet finder to task.
   jetana->SetJetFinder(jetFinder);
   jetana->SetConfigFile("");
   jetana->SetDebugLevel(10);
   mgr->AddTask(jetana);

   // Create ONLY the output containers for the data produced by the task.
   // Get and connect other common input/output containers via the manager as below
   //==============================================================================
   mgr->ConnectInput  (jetana, 0, mgr->GetCommonInputContainer());
// AOD output slot will be used in a different way in future
   mgr->ConnectOutput (jetana, 0, mgr->GetCommonOutputContainer());
   mgr->ConnectOutput (jetana, 1, cout_jet);

   return jetana;
}

AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius){

  switch (jf) {
  case "CDF":
    AliCdfJetHeader *jh = new AliCdfJetHeader();
    jh->SetRadius(0.7);

    jetFinder = new AliCdfJetFinder();
    jetFinder->SetOutputFile("jets.root");
    if (jh) jetFinder->SetJetHeader(jh);
    break;

  case "DA":
    AliDAJetHeader *jh=new AliDAJetHeader();
    jh->SetComment("DA jet code with default parameters");
    jh->SelectJets(kTRUE);
    jh->SetNclust(10);

    jetFinder = new AliDAJetFinder();
    if (jh) jetFinder->SetJetHeader(jh);
    break;

  case "Fastjet":
    AliFastJetHeader *jh = new AliFastJetHeader();
    jh->SetRparam(0.7); // setup parameters

    jetFinder = new AliFastJetFinder();
    jetFinder->SetOutputFile("jets.root");
    if (jh) jetFinder->SetJetHeader(jh);
    break;

  case "UA1":
    AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1();
    jh->SetComment("UA1 jet code with default parameters");
    jh->BackgMode(0);
    jh->SetRadius(0.4);
    if(radius>0)jh->SetRadius(radius);
    jh->SetEtSeed(4.);
    jh->SetLegoNbinPhi(432);
    jh->SetLegoNbinEta(274);
    jh->SetLegoEtaMin(-2);
    jh->SetLegoEtaMax(+2);
    jh->SetMinJetEt(10.);
    jh->SetJetEtaMax(1.5);
    jh->SetJetEtaMin(-1.5);

    jetFinder = new AliUA1JetFinderV1();
    if (jh) jetFinder->SetJetHeader(jh);
    break;

  case "UA1MC":
    AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1();
    jh->SetComment("UA1 jet code with default MC parameters");
    jh->BackgMode(0);
    jh->SetRadius(1.0);
    if(radius>0)jh->SetRadius(radius);
    jh->SetEtSeed(4.);
    jh->SetLegoNbinPhi(432);
    jh->SetLegoNbinEta(274);
    jh->SetLegoEtaMin(-2);
    jh->SetLegoEtaMax(+2);
    jh->SetMinJetEt(10.);
    jh->SetJetEtaMax(1.5);
    jh->SetJetEtaMin(-1.5);

    jetFinder = new AliUA1JetFinderV1();
    if (jh) jetFinder->SetJetHeader(jh);
    break;
  case default:
    ::Error("AddTaskJets", "Wrong jet finder selected\n");
    return 0;
  }

  return jetFinder;

}

AliJetReader *CreateJetReader(Char_t *jr){
  AliJetReader *er = 0;

  switch (jr) {
  case "MC":
    AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader();
    jrh->SetComment("MC full Kinematics");
    jrh->SetFastSimTPC(kFALSE);
    jrh->SetFastSimEMCAL(kFALSE);
    jrh->SetPtCut(0.);
    jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9
    // Define reader and set its header
    er = new AliJetKineReader();
    er->SetReaderHeader(jrh);
    break;
  case "MC2":
    AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader();
    jrh->SetComment("MC full Kinematics spearate config");
    jrh->SetFastSimTPC(kFALSE);
    jrh->SetFastSimEMCAL(kFALSE);
    jrh->SetPtCut(0.);
    jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9
    // Define reader and set its header
    er = new AliJetKineReader();
    er->SetReaderHeader(jrh);
    break;
  case "ESD":
    AliJetESDReaderHeader *jrh = new AliJetESDReaderHeader();
    jrh->SetComment("Testing");
    jrh->SetFirstEvent(0);
    jrh->SetLastEvent(1000);
    jrh->SetPtCut(0.);
    jrh->SetReadSignalOnly(kFALSE);
    // Define reader and set its header
    er = new AliJetESDReader();
    er->SetReaderHeader(jrh);
    break;

  case "AOD":
    AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader();
    jrh->SetComment("AOD Reader");
    jrh->SetPtCut(0.);
    jrh->SetTestFilterMask(1<<0);
    // Define reader and set its header
    er = new AliJetAODReader();
    er->SetReaderHeader(jrh);
    break;

  default:
    ::Error("AddTaskJets", "Wrong jet reader selected\n");
    return 0;
  }

  return er;

}
<|endoftext|>