<commit_before>#pragma once

#include "Defines.hpp"
#include "Allocator.hpp"

namespace Poly {

	namespace ObjectLifetimeHelper
	{
		// Not really sure if this is needed
		template<class T>
		void DefaultCreate(T* ptr, typename std::enable_if<std::is_trivially_default_constructible<T>::value>::type* = 0)
		{
			::new (ptr)T; // TODO use memcpy here
		}

		template<class T>
		void DefaultCreate(T* ptr, typename std::enable_if<!std::is_trivially_default_constructible<T>::value>::type* = 0)
		{
			::new (ptr)T;
		}

		template<class T>
		void CopyCreate(T* ptr, const T& obj, typename std::enable_if<std::is_trivially_copy_constructible<T>::value>::type* = 0)
		{
			::new (ptr)T(obj); // TODO use memcpy here
		}

		template<class T>
		void CopyCreate(T* ptr, const T& obj, typename std::enable_if<!std::is_trivially_copy_constructible<T>::value>::type* = 0)
		{
			::new (ptr)T(obj);
		}

		template<class T>
		void Destroy(T* t, typename std::enable_if<std::is_trivially_destructible<T>::value>::type* = 0)
		{
			t->~T(); // calling destructor here is unnecessary
		}

		template<class T>
		void Destroy(T* t, typename std::enable_if<!std::is_trivially_destructible<T>::value>::type* = 0)
		{
			t->~T();
		}
	}

	template<typename T>
	class Dynarray : public BaseObject<>
	{
	public:
		class Iterator : public BaseObject<>
		{
		public:
			bool operator==(const Iterator& rhs) const { return Data == rhs.Data && Idx == rhs.Idx; }
			bool operator!=(const Iterator& rhs) const { return !(*this == rhs); }

			T& operator*() const { return Data[Idx]; }
			T& operator->() const { return Data[Idx]; }

			Iterator& operator++() { ++Idx; return *this; }
			Iterator operator++(int) { Iterator ret(Data, Idx); ++Idx; return ret; }
			Iterator& operator--() { --Idx; return *this; }
			Iterator operator--(int) { Iterator ret(Data, Idx); --Idx; return ret; }

			Iterator operator+(size_t val) const { return Iterator(Data, Idx + val); }
			Iterator operator-(size_t val) const { return Iterator(Data, Idx - val); }
			Iterator& operator+=(size_t val) { Idx += val; return *this; }
			Iterator& operator-=(size_t val) { Idx -= val; return *this; }
		private:
			Iterator(T* data, size_t idx) : Data(data), Idx(idx) {}

			size_t Idx = 0;
			T* Data = nullptr;
			friend class Dynarray<T>;
		};

		class ConstIterator : public BaseObject<>
		{
		public:
			bool operator==(const ConstIterator& rhs) const { return Data == rhs.Data && Idx == rhs.Idx; }
			bool operator!=(const ConstIterator& rhs) const { return !(*this == rhs); }

			const T& operator*() const { return Data[Idx]; }
			const T& operator->() const { return Data[Idx]; }

			ConstIterator& operator++() { ++Idx; return *this; }
			ConstIterator operator++(int) { ConstIterator ret(Data, Idx); ++Idx; return ret; }
			ConstIterator& operator--() { --Idx; return *this; }
			ConstIterator operator--(int) { ConstIterator ret(Data, Idx); --Idx; return ret; }

			ConstIterator operator+(size_t val) const { return ConstIterator(Data, Idx + val); }
			ConstIterator operator-(size_t val) const { return ConstIterator(Data, Idx - val); }
			ConstIterator& operator+=(size_t val) { Idx += val; return *this; }
			ConstIterator& operator-=(size_t val) { Idx -= val; return *this; }
		private:
			ConstIterator(const T* data, size_t idx) : Data(data), Idx(idx) {}

			size_t Idx = 0;
			const T* Data = nullptr;
			friend class Dynarray<T>;
		};

		//------------------------------------------------------------------------------
		Dynarray() = default;
		Dynarray(size_t capacity) { Reserve(capacity); }

		//------------------------------------------------------------------------------
		Dynarray(const Dynarray<T>& rhs)
		{
			Copy(rhs);
		}

		//------------------------------------------------------------------------------
		Dynarray(Dynarray<T>&& rhs)
		{
			Move(std::forward<Dynarray<T>>(rhs));
		}

		//------------------------------------------------------------------------------
		Dynarray(const std::initializer_list<T>& list)
		{
			PopulateFromInitializerList(list);
		}

		//------------------------------------------------------------------------------
		~Dynarray()
		{
			Clear();
			Free();
		}

		//------------------------------------------------------------------------------
		Dynarray<T>& operator=(const Dynarray<T>& rhs)
		{
			Clear();
			Copy(rhs);
			return *this;
		}

		//------------------------------------------------------------------------------
		Dynarray<T>& operator=(Dynarray<T>&& rhs)
		{
			Clear();
			Free();
			Move(std::forward<Dynarray<T>>(rhs));
			return *this;
		}

		//------------------------------------------------------------------------------
		Dynarray<T>& operator=(const std::initializer_list<T>& list)
		{
			Clear();
			PopulateFromInitializerList(list);
			return *this;
		}

		//------------------------------------------------------------------------------
		bool operator==(const Dynarray<T>& rhs) const
		{
			if (GetSize() != rhs.GetSize())
				return false;

			for (size_t idx = 0; idx < GetSize(); ++idx)
				if (Data[idx] != rhs.Data[idx])
					return false;

			return true;
		}

		bool operator!=(const Dynarray<T>& rhs) const { return !(*this == rhs); };

		//------------------------------------------------------------------------------
		bool IsEmpty() const { return GetSize() == 0; }
		size_t GetSize() const { return Size; }
		size_t GetCapacity() const { return Capacity; }
		T* GetData() { return Data; }
		const T* GetData() const { return Data; }

		//------------------------------------------------------------------------------
		T& operator[](size_t idx) { HEAVY_ASSERTE(idx < GetSize(), "Index out of bounds!"); return Data[idx]; }
		const T& operator[](size_t idx) const { HEAVY_ASSERTE(idx < GetSize(), "Index out of bounds!"); return Data[idx]; }

		//------------------------------------------------------------------------------
		void Clear() {
			for (size_t idx = 0; idx < GetSize(); ++idx)
				ObjectLifetimeHelper::Destroy(Data + idx);
			Size = 0;
		}

		//------------------------------------------------------------------------------
		void Insert(size_t idx, const T& obj)
		{
			HEAVY_ASSERTE(idx <= GetSize(), "Index out of bounds!");
			if (Size == GetCapacity())
				Enlarge();
			memmove(Data + idx + 1, Data + idx, (GetSize() - idx) * sizeof(T));
			ObjectLifetimeHelper::CopyCreate(Data + idx, obj);
			++Size;
		}

		//------------------------------------------------------------------------------
		void Remove(size_t idx)
		{
			HEAVY_ASSERTE(idx < GetSize(), "Index out of bounds!");
			ObjectLifetimeHelper::Destroy(Data + idx);
			memmove(Data + idx, Data + idx + 1, (GetSize() - idx - 1) * sizeof(T));
			--Size;
		}

		//------------------------------------------------------------------------------
		void PushBack(const T& obj) { Insert(GetSize(), obj); }
		void PopBack() { Remove(GetSize() - 1); }
		void PushFront(const T& obj) { Insert(0, obj); }
		void PopFront() { Remove(0); }

		//------------------------------------------------------------------------------
		void Resize(size_t size)
		{
			if (size == GetSize())
				return;

			if (size < GetSize())
			{
				// remove excessive elements
				for (size_t idx = GetSize(); idx < size; ++idx)
					ObjectLifetimeHelper::Destroy(Data + idx);
			}
			else
			{
				Reserve(size);
				for (size_t idx = GetSize(); idx < size; ++idx)
					ObjectLifetimeHelper::DefaultCreate(Data + idx);
			}
			Size = size;
		}

		//------------------------------------------------------------------------------
		void Reserve(size_t capacity)
		{
			if (capacity <= Capacity)
				return;
			Realloc(capacity * sizeof(T));
		}

		//------------------------------------------------------------------------------
		Iterator Begin() { return Iterator(Data, 0); }
		Iterator End() { return Iterator(Data, GetSize()); }
		ConstIterator Begin() const { return ConstIterator(Data, 0); }
		ConstIterator End() const { return ConstIterator(Data, GetSize()); }

	private:
		//------------------------------------------------------------------------------
		void Realloc(size_t capacity)
		{
			Data = static_cast<T*>(DefaultRealloc(Data, capacity * sizeof(T)));
			Capacity = capacity;
		}

		void Free() { if (Data) DefaultFree(Data); }

		//------------------------------------------------------------------------------
		void Copy(const Dynarray<T>& rhs)
		{
			Reserve(rhs.GetSize());
			for (size_t idx = 0; idx < rhs.GetSize(); ++idx)
				PushBack(rhs.Data[idx]);
		}

		//------------------------------------------------------------------------------
		void Move(Dynarray<T>&& rhs)
		{
			Size = rhs.Size;
			Capacity = rhs.Capacity;
			Data = rhs.Data;
			rhs.Data = nullptr;
			rhs.Size = 0;
			rhs.Capacity = 0;
		}

		//------------------------------------------------------------------------------
		void PopulateFromInitializerList(const std::initializer_list<T>& list)
		{
			Reserve(list.size());
			for (const T& obj : list)
				PushBack(obj);
		}

		void Enlarge() { Reserve((Capacity + 1) * 2); }

		size_t Size = 0;
		size_t Capacity = 0;
		T* Data = nullptr;
	};

	// std library for each enablers
	template <typename T> typename Poly::Dynarray<T>::Iterator begin(Poly::Dynarray<T>& rhs) { return rhs.Begin(); }
	template <typename T> typename Poly::Dynarray<T>::Iterator end(Poly::Dynarray<T>& rhs) { return rhs.End(); }
	template <typename T> typename Poly::Dynarray<T>::ConstIterator begin(const Poly::Dynarray<T>& rhs) { return rhs.Begin(); }
	template <typename T> typename Poly::Dynarray<T>::ConstIterator end(const Poly::Dynarray<T>& rhs) { return rhs.End(); }
}
<commit_msg>Dynarray API improvements.<commit_after>#pragma once

#include "Defines.hpp"
#include "Allocator.hpp"

namespace Poly {

	namespace ObjectLifetimeHelper
	{
		// Not really sure if this is needed
		template<class T>
		void DefaultCreate(T* ptr, typename std::enable_if<std::is_trivially_default_constructible<T>::value>::type* = 0)
		{
			::new (ptr)T; // TODO use memcpy here
		}

		template<class T>
		void DefaultCreate(T* ptr, typename std::enable_if<!std::is_trivially_default_constructible<T>::value>::type* = 0)
		{
			::new (ptr)T;
		}

		template<class T>
		void CopyCreate(T* ptr, const T& obj, typename std::enable_if<std::is_trivially_copy_constructible<T>::value>::type* = 0)
		{
			::new (ptr)T(obj); // TODO use memcpy here
		}

		template<class T>
		void CopyCreate(T* ptr, const T& obj, typename std::enable_if<!std::is_trivially_copy_constructible<T>::value>::type* = 0)
		{
			::new (ptr)T(obj);
		}

		template<class T>
		void Destroy(T* t, typename std::enable_if<std::is_trivially_destructible<T>::value>::type* = 0)
		{
			t->~T(); // calling destructor here is unnecessary
		}

		template<class T>
		void Destroy(T* t, typename std::enable_if<!std::is_trivially_destructible<T>::value>::type* = 0)
		{
			t->~T();
		}
	}

	template<typename T>
	class Dynarray : public BaseObject<>
	{
	public:
		class Iterator : public BaseObject<>
		{
		public:
			bool operator==(const Iterator& rhs) const { return Data == rhs.Data && Idx == rhs.Idx; }
			bool operator!=(const Iterator& rhs) const { return !(*this == rhs); }

			T& operator*() const { return Data[Idx]; }
			T& operator->() const { return Data[Idx]; }

			Iterator& operator++() { ++Idx; return *this; }
			Iterator operator++(int) { Iterator ret(Data, Idx); ++Idx; return ret; }
			Iterator& operator--() { --Idx; return *this; }
			Iterator operator--(int) { Iterator ret(Data, Idx); --Idx; return ret; }

			Iterator operator+(size_t val) const { return Iterator(Data, Idx + val); }
			Iterator operator-(size_t val) const { return Iterator(Data, Idx - val); }
			Iterator& operator+=(size_t val) { Idx += val; return *this; }
			Iterator& operator-=(size_t val) { Idx -= val; return *this; }
		private:
			Iterator(T* data, size_t idx) : Data(data), Idx(idx) {}

			size_t Idx = 0;
			T* Data = nullptr;
			friend class Dynarray<T>;
		};

		class ConstIterator : public BaseObject<>
		{
		public:
			bool operator==(const ConstIterator& rhs) const { return Data == rhs.Data && Idx == rhs.Idx; }
			bool operator!=(const ConstIterator& rhs) const { return !(*this == rhs); }

			const T& operator*() const { return Data[Idx]; }
			const T& operator->() const { return Data[Idx]; }

			ConstIterator& operator++() { ++Idx; return *this; }
			ConstIterator operator++(int) { ConstIterator ret(Data, Idx); ++Idx; return ret; }
			ConstIterator& operator--() { --Idx; return *this; }
			ConstIterator operator--(int) { ConstIterator ret(Data, Idx); --Idx; return ret; }

			ConstIterator operator+(size_t val) const { return ConstIterator(Data, Idx + val); }
			ConstIterator operator-(size_t val) const { return ConstIterator(Data, Idx - val); }
			ConstIterator& operator+=(size_t val) { Idx += val; return *this; }
			ConstIterator& operator-=(size_t val) { Idx -= val; return *this; }
		private:
			ConstIterator(const T* data, size_t idx) : Data(data), Idx(idx) {}

			size_t Idx = 0;
			const T* Data = nullptr;
			friend class Dynarray<T>;
		};

		//------------------------------------------------------------------------------
		Dynarray() = default;
		Dynarray(size_t capacity) { Reserve(capacity); }

		//------------------------------------------------------------------------------
		Dynarray(const Dynarray<T>& rhs)
		{
			Copy(rhs);
		}

		//------------------------------------------------------------------------------
		Dynarray(Dynarray<T>&& rhs)
		{
			Move(std::forward<Dynarray<T>>(rhs));
		}

		//------------------------------------------------------------------------------
		Dynarray(const std::initializer_list<T>& list)
		{
			PopulateFromInitializerList(list);
		}

		//------------------------------------------------------------------------------
		~Dynarray()
		{
			Clear();
			Free();
		}

		//------------------------------------------------------------------------------
		Dynarray<T>& operator=(const Dynarray<T>& rhs)
		{
			Clear();
			Copy(rhs);
			return *this;
		}

		//------------------------------------------------------------------------------
		Dynarray<T>& operator=(Dynarray<T>&& rhs)
		{
			Clear();
			Free();
			Move(std::forward<Dynarray<T>>(rhs));
			return *this;
		}

		//------------------------------------------------------------------------------
		Dynarray<T>& operator=(const std::initializer_list<T>& list)
		{
			Clear();
			PopulateFromInitializerList(list);
			return *this;
		}

		//------------------------------------------------------------------------------
		bool operator==(const Dynarray<T>& rhs) const
		{
			if (GetSize() != rhs.GetSize())
				return false;

			for (size_t idx = 0; idx < GetSize(); ++idx)
				if (Data[idx] != rhs.Data[idx])
					return false;

			return true;
		}

		bool operator!=(const Dynarray<T>& rhs) const { return !(*this == rhs); };

		//------------------------------------------------------------------------------
		bool IsEmpty() const { return GetSize() == 0; }
		size_t GetSize() const { return Size; }
		size_t GetCapacity() const { return Capacity; }
		T* GetData() { return Data; }
		const T* GetData() const { return Data; }

		//------------------------------------------------------------------------------
		T& operator[](size_t idx) { HEAVY_ASSERTE(idx < GetSize(), "Index out of bounds!"); return Data[idx]; }
		const T& operator[](size_t idx) const { HEAVY_ASSERTE(idx < GetSize(), "Index out of bounds!"); return Data[idx]; }

		//------------------------------------------------------------------------------
		void Clear() {
			for (size_t idx = 0; idx < GetSize(); ++idx)
				ObjectLifetimeHelper::Destroy(Data + idx);
			Size = 0;
		}

		//------------------------------------------------------------------------------
		void Insert(size_t idx, const T& obj)
		{
			HEAVY_ASSERTE(idx <= GetSize(), "Index out of bounds!");
			if (Size == GetCapacity())
				Enlarge();
			memmove(Data + idx + 1, Data + idx, (GetSize() - idx) * sizeof(T));
			ObjectLifetimeHelper::CopyCreate(Data + idx, obj);
			++Size;
		}

		//------------------------------------------------------------------------------
		void RemoveByIdx(size_t idx)
		{
			HEAVY_ASSERTE(idx < GetSize(), "Index out of bounds!");
			ObjectLifetimeHelper::Destroy(Data + idx);
			memmove(Data + idx, Data + idx + 1, (GetSize() - idx - 1) * sizeof(T));
			--Size;
		}

		//------------------------------------------------------------------------------
		size_t FindIdx(const T& rhs) const
		{
			for (size_t idx = 0; idx < GetSize(); ++idx)
			{
				if (Data[idx] == rhs)
					return idx;
			}
			return GetSize();
		}

		//------------------------------------------------------------------------------
		void PushBack(const T& obj) { Insert(GetSize(), obj); }
		void PopBack() { RemoveByIdx(GetSize() - 1); }
		void PushFront(const T& obj) { Insert(0, obj); }
		void PopFront() { RemoveByIdx(0); }

		//------------------------------------------------------------------------------
		void Resize(size_t size)
		{
			if (size == GetSize())
				return;

			if (size < GetSize())
			{
				// remove excessive elements
				for (size_t idx = GetSize(); idx < size; ++idx)
					ObjectLifetimeHelper::Destroy(Data + idx);
			}
			else
			{
				Reserve(size);
				for (size_t idx = GetSize(); idx < size; ++idx)
					ObjectLifetimeHelper::DefaultCreate(Data + idx);
			}
			Size = size;
		}

		//------------------------------------------------------------------------------
		void Reserve(size_t capacity)
		{
			if (capacity <= Capacity)
				return;
			Realloc(capacity * sizeof(T));
		}

		//------------------------------------------------------------------------------
		Iterator Begin() { return Iterator(Data, 0); }
		Iterator End() { return Iterator(Data, GetSize()); }
		ConstIterator Begin() const { return ConstIterator(Data, 0); }
		ConstIterator End() const { return ConstIterator(Data, GetSize()); }

		//------------------------------------------------------------------------------
		Iterator Find(const T& rhs) { return Iterator(Data, FindIdx(rhs)); }
		ConstIterator Find(const T& rhs) const { return ConstIterator(Data, FindIdx(rhs)); }

		//------------------------------------------------------------------------------
		bool Contains(const T& rhs) const { return FindIdx(rhs) < GetSize(); }
		void Remove(const T& rhs) { RemoveByIdx(FindIdx(rhs)); }
		bool TryRemove(const T& rhs)
		{
			size_t idx = FindIdx(rhs);
			if (idx < GetSize())
			{
				RemoveByIdx(idx);
				return true;
			}
			return false;
		}

	private:
		//------------------------------------------------------------------------------
		void Realloc(size_t capacity)
		{
			Data = static_cast<T*>(DefaultRealloc(Data, capacity * sizeof(T)));
			Capacity = capacity;
		}

		void Free() { if (Data) DefaultFree(Data); }

		//------------------------------------------------------------------------------
		void Copy(const Dynarray<T>& rhs)
		{
			Reserve(rhs.GetSize());
			for (size_t idx = 0; idx < rhs.GetSize(); ++idx)
				PushBack(rhs.Data[idx]);
		}

		//------------------------------------------------------------------------------
		void Move(Dynarray<T>&& rhs)
		{
			Size = rhs.Size;
			Capacity = rhs.Capacity;
			Data = rhs.Data;
			rhs.Data = nullptr;
			rhs.Size = 0;
			rhs.Capacity = 0;
		}

		//------------------------------------------------------------------------------
		void PopulateFromInitializerList(const std::initializer_list<T>& list)
		{
			Reserve(list.size());
			for (const T& obj : list)
				PushBack(obj);
		}

		void Enlarge() { Reserve((Capacity + 1) * 2); }

		size_t Size = 0;
		size_t Capacity = 0;
		T* Data = nullptr;
	};

	// std library for each enablers
	template <typename T> typename Poly::Dynarray<T>::Iterator begin(Poly::Dynarray<T>& rhs) { return rhs.Begin(); }
	template <typename T> typename Poly::Dynarray<T>::Iterator end(Poly::Dynarray<T>& rhs) { return rhs.End(); }
	template <typename T> typename Poly::Dynarray<T>::ConstIterator begin(const Poly::Dynarray<T>& rhs) { return rhs.Begin(); }
	template <typename T> typename Poly::Dynarray<T>::ConstIterator end(const Poly::Dynarray<T>& rhs) { return rhs.End(); }
}
<|endoftext|>


<commit_before>// =============================================================================
//
// Copyright (c) 2014 Christopher Baker <http://christopherbaker.net>
//
// 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 "ofApp.h"

void ofApp::setup()
{
    ofSetFrameRate(30);
    ofEnableAlphaBlending();

    /// Example Database
    std::string filename_example_db3 = ofToDataPath("example.db3", true);
    std::string filename_logo_png    = ofToDataPath("logo.png", true);
    std::string transactionDb = ofToDataPath("transaction.db3", true);
    std::string testDb = ofToDataPath("test.db3", true);

    // Basic example (1/6) :
    try
    {
        // Open a database file in readonly mode
        SQLite::Database db(filename_example_db3);  // SQLITE_OPEN_READONLY
        std::cout << "SQLite database file '" << db.getFilename().c_str() << "' opened successfully\n";

        // Test if the 'test' table exists
        bool bExists = db.tableExists("test");
        std::cout << "SQLite table 'test' exists=" << bExists << "\n";

        // Get a single value result with an easy to use shortcut
        std::string value = db.execAndGet("SELECT value FROM test WHERE id = 2");
        std::cout << "execAndGet=" << value.c_str() << std::endl;

        // Compile a SQL query, containing one parameter (index 1)
        SQLite::Statement query(db, "SELECT id as test_id, value as test_val, weight as test_weight FROM test WHERE weight > ?");

        std::cout << "SQLite statement '" << query.getQuery() << "' compiled (" << query.getColumnCount() << " columns in the result)\n";

        // Bind the integer value 2 to the first parameter of the SQL query
        query.bind(1, 2);
        std::cout << "binded with integer value '2' :\n";

        // Loop to execute the query step by step, to get one a row of results at a time
        while (query.executeStep())
        {
            // Demonstrate how to get some typed column value (and the equivalent explicit call)
            int         id      = query.getColumn(0); // = query.getColumn(0).getInt()
            std::string value2  = query.getColumn(1); // = query.getColumn(1).getText()
            int         bytes   = query.getColumn(1).getBytes();
            double      weight  = query.getColumn(2); // = query.getColumn(2).getInt()

            static bool bFirst = true;
            if (bFirst)
            {
                // Show how to get the aliased names of the result columns.
                std::string name0 = query.getColumn(0).getName();
                std::string name1 = query.getColumn(1).getName();
                std::string name2 = query.getColumn(2).getName();
                std::cout << "aliased result [\"" << name0.c_str() << "\", \"" << name1.c_str() << "\", \"" << name2.c_str() << "\"]\n";

                bFirst = false;
            }

            std::cout << "row (" << id << ", \"" << value2.c_str() << "\" "  << bytes << " bytes, " << weight << ")\n";
        }

        // Reset the query to use it again
        query.reset();

        std::cout << "SQLite statement '" << query.getQuery() << "' reseted (" << query.getColumnCount () << " columns in the result)\n";
        // Bind the string value "6" to the first parameter of the SQL query
        query.bind(1, "6");
        std::cout << "binded with string value \"6\" :\n";

        while (query.executeStep())
        {
            // Demonstrate that inserting column value in a std:ostream is natural
            std::cout << "row (" << query.getColumn(0) << ", \"" << query.getColumn(1) << "\", " << query.getColumn(2) << ")\n";
        }
    }
    catch (std::exception& e)
    {
        std::cout << "SQLite exception: " << e.what() << std::endl;
        return EXIT_FAILURE; // unexpected error : exit the example program
    }

    ////////////////////////////////////////////////////////////////////////////
    // Object Oriented Basic example (2/6) :
    try
    {
        // Open the database and compile the query
        Example example(filename_example_db3);

        // Demonstrate the way to use the same query with different parameter values
        example.ListGreaterThan(8);
        example.ListGreaterThan(6);
        example.ListGreaterThan(2);
    }
    catch (std::exception& e)
    {
        std::cout << "SQLite exception: " << e.what() << std::endl;
        return EXIT_FAILURE; // unexpected error : exit the example program
    }

    // The execAndGet wrapper example (3/6) :
    try
    {
        // Open a database file in readonly mode
        SQLite::Database  db(filename_example_db3);  // SQLITE_OPEN_READONLY
        std::cout << "SQLite database file '" << db.getFilename().c_str() << "' opened successfully\n";

        // WARNING: Be very careful with this dangerous method: you have to
        // make a COPY OF THE result, else it will be destroy before the next line
        // (when the underlying temporary Statement and Column objects are destroyed)
        std::string value = db.execAndGet("SELECT value FROM test WHERE id=2");
        std::cout << "execAndGet=" << value.c_str() << std::endl;
    }
    catch (std::exception& e)
    {
        std::cout << "SQLite exception: " << e.what() << std::endl;
        return EXIT_FAILURE; // unexpected error : exit the example program
    }

    ////////////////////////////////////////////////////////////////////////////
    // Simple batch queries example (4/6) :
    try
    {
        // Open a database file in create/write mode
        SQLite::Database    db(testDb, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
        std::cout << "SQLite database file '" << db.getFilename().c_str() << "' opened successfully\n";

        db.exec("DROP TABLE IF EXISTS test");

        db.exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)");

        // first row
        int nb = db.exec("INSERT INTO test VALUES (NULL, \"test\")");
        std::cout << "INSERT INTO test VALUES (NULL, \"test\")\", returned " << nb << std::endl;

        // second row
        nb = db.exec("INSERT INTO test VALUES (NULL, \"second\")");
        std::cout << "INSERT INTO test VALUES (NULL, \"second\")\", returned " << nb << std::endl;

        // update the second row
        nb = db.exec("UPDATE test SET value=\"second-updated\" WHERE id='2'");
        std::cout << "UPDATE test SET value=\"second-updated\" WHERE id='2', returned " << nb << std::endl;

        // Check the results : expect two row of result
        SQLite::Statement   query(db, "SELECT * FROM test");
        std::cout << "SELECT * FROM test :\n";
        while (query.executeStep())
        {
            std::cout << "row (" << query.getColumn(0) << ", \"" << query.getColumn(1) << "\")\n";
        }

        db.exec("DROP TABLE test");
    }
    catch (std::exception& e)
    {
        std::cout << "SQLite exception: " << e.what() << std::endl;
        return EXIT_FAILURE; // unexpected error : exit the example program
    }

    remove(testDb.c_str());

    ////////////////////////////////////////////////////////////////////////////
    // RAII transaction example (5/6) :
    try
    {
        // Open a database file in create/write mode
        SQLite::Database db(transactionDb, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
        std::cout << "SQLite database file '" << db.getFilename().c_str() << "' opened successfully\n";

        db.exec("DROP TABLE IF EXISTS test");

        // Exemple of a successful transaction :
        try
        {
            // Begin transaction
            SQLite::Transaction transaction(db);

            db.exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)");

            int nb = db.exec("INSERT INTO test VALUES (NULL, \"test\")");
            std::cout << "INSERT INTO test VALUES (NULL, \"test\")\", returned " << nb << std::endl;

            // Commit transaction
            transaction.commit();
        }
        catch (std::exception& e)
        {
            std::cout << "SQLite exception: " << e.what() << std::endl;
            return EXIT_FAILURE; // unexpected error : exit the example program
        }

        // Exemple of a rollbacked transaction :
        try
        {
            // Begin transaction
            SQLite::Transaction transaction(db);

            int nb = db.exec("INSERT INTO test VALUES (NULL, \"second\")");

            std::cout << "INSERT INTO test VALUES (NULL, \"second\")\", returned " << nb << std::endl;

            nb = db.exec("INSERT INTO test ObviousError");
            std::cout << "INSERT INTO test \"error\", returned " << nb << std::endl;

            return EXIT_FAILURE; // unexpected success : exit the example program

            // Commit transaction
            transaction.commit();
        }
        catch (std::exception& e)
        {
            std::cout << "SQLite exception: " << e.what() << std::endl;
            // expected error, see above
        }

        // Check the results (expect only one row of result, as the second one has been rollbacked by the error)
        SQLite::Statement   query(db, "SELECT * FROM test");
        std::cout << "SELECT * FROM test :\n";
        while (query.executeStep())
        {
            std::cout << "row (" << query.getColumn(0) << ", \"" << query.getColumn(1) << "\")\n";
        }
    }
    catch (std::exception& e)
    {
        std::cout << "SQLite exception: " << e.what() << std::endl;
        return EXIT_FAILURE; // unexpected error : exit the example program
    }

    remove(transactionDb.c_str());

    ////////////////////////////////////////////////////////////////////////////
    // Binary blob and in-memory database example (6/6) :
    try
    {
        // Open a database file in create/write mode
        SQLite::Database  db(":memory:", SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
        std::cout << "SQLite database file '" << db.getFilename().c_str() << "' opened successfully\n";

        db.exec("DROP TABLE IF EXISTS test");
        db.exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value BLOB)");

        FILE* fp = fopen(filename_logo_png.c_str(), "rb");
        if (NULL != fp)
        {
            char  buffer[16*1024];
            void* blob = &buffer;
            int size = static_cast<int>(fread(blob, 1, 16*1024, fp));
            buffer[size] = '\0';
            fclose (fp);
            std::cout << "blob size=" << size << " :\n";

            // Insert query
            SQLite::Statement   query(db, "INSERT INTO test VALUES (NULL, ?)");
            // Bind the blob value to the first parameter of the SQL query
            query.bind(1, blob, size);
            std::cout << "blob binded successfully\n";

            // Execute the one-step query to insert the blob
            int nb = query.exec ();
            std::cout << "INSERT INTO test VALUES (NULL, ?)\", returned " << nb << std::endl;
        }
        else
        {
            std::cout << "file " << filename_logo_png << " not found !\n";
            return EXIT_FAILURE; // unexpected error : exit the example program
        }

        fp = fopen(ofToDataPath("out.png", true).c_str(), "wb");
        if (NULL != fp)
        {
            const void* blob = NULL;
            size_t size;

            SQLite::Statement   query(db, "SELECT * FROM test");
            std::cout << "SELECT * FROM test :\n";
            if (query.executeStep())
            {
                SQLite::Column colBlob = query.getColumn(1);
                blob = colBlob.getBlob();
                size = colBlob.getBytes();
                std::cout << "row (" << query.getColumn(0) << ", size=" << size << ")\n";
                size_t sizew = fwrite(blob, 1, size, fp);
                SQLITECPP_ASSERT(sizew == size, "fwrite failed");   // See SQLITECPP_ENABLE_ASSERT_HANDLER
                fclose (fp);
            }
        }
        else
        {
            std::cout << "file out.png not created !\n";
            return EXIT_FAILURE; // unexpected error : exit the example program
        }
    }
    catch (std::exception& e)
    {
        std::cout << "SQLite exception: " << e.what() << std::endl;
        return EXIT_FAILURE; // unexpected error : exit the example program
    }

    remove(ofToDataPath("out.png", true).c_str());

    std::cout << "everything ok, quitting\n";

}

void ofApp::draw()
{
    ofBackgroundGradient(ofColor::white, ofColor::black);

}
<commit_msg>Removed returns.<commit_after>// =============================================================================
//
// Copyright (c) 2014 Christopher Baker <http://christopherbaker.net>
//
// 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 "ofApp.h"

void ofApp::setup()
{
    ofSetFrameRate(30);
    ofEnableAlphaBlending();

    /// Example Database
    std::string filename_example_db3 = ofToDataPath("example.db3", true);
    std::string filename_logo_png    = ofToDataPath("logo.png", true);
    std::string transactionDb = ofToDataPath("transaction.db3", true);
    std::string testDb = ofToDataPath("test.db3", true);

    // Basic example (1/6) :
    try
    {
        // Open a database file in readonly mode
        SQLite::Database db(filename_example_db3);  // SQLITE_OPEN_READONLY
        std::cout << "SQLite database file '" << db.getFilename().c_str() << "' opened successfully\n";

        // Test if the 'test' table exists
        bool bExists = db.tableExists("test");
        std::cout << "SQLite table 'test' exists=" << bExists << "\n";

        // Get a single value result with an easy to use shortcut
        std::string value = db.execAndGet("SELECT value FROM test WHERE id = 2");
        std::cout << "execAndGet=" << value.c_str() << std::endl;

        // Compile a SQL query, containing one parameter (index 1)
        SQLite::Statement query(db, "SELECT id as test_id, value as test_val, weight as test_weight FROM test WHERE weight > ?");

        std::cout << "SQLite statement '" << query.getQuery() << "' compiled (" << query.getColumnCount() << " columns in the result)\n";

        // Bind the integer value 2 to the first parameter of the SQL query
        query.bind(1, 2);
        std::cout << "binded with integer value '2' :\n";

        // Loop to execute the query step by step, to get one a row of results at a time
        while (query.executeStep())
        {
            // Demonstrate how to get some typed column value (and the equivalent explicit call)
            int         id      = query.getColumn(0); // = query.getColumn(0).getInt()
            std::string value2  = query.getColumn(1); // = query.getColumn(1).getText()
            int         bytes   = query.getColumn(1).getBytes();
            double      weight  = query.getColumn(2); // = query.getColumn(2).getInt()

            static bool bFirst = true;
            if (bFirst)
            {
                // Show how to get the aliased names of the result columns.
                std::string name0 = query.getColumn(0).getName();
                std::string name1 = query.getColumn(1).getName();
                std::string name2 = query.getColumn(2).getName();
                std::cout << "aliased result [\"" << name0.c_str() << "\", \"" << name1.c_str() << "\", \"" << name2.c_str() << "\"]\n";

                bFirst = false;
            }

            std::cout << "row (" << id << ", \"" << value2.c_str() << "\" "  << bytes << " bytes, " << weight << ")\n";
        }

        // Reset the query to use it again
        query.reset();

        std::cout << "SQLite statement '" << query.getQuery() << "' reseted (" << query.getColumnCount () << " columns in the result)\n";
        // Bind the string value "6" to the first parameter of the SQL query
        query.bind(1, "6");
        std::cout << "binded with string value \"6\" :\n";

        while (query.executeStep())
        {
            // Demonstrate that inserting column value in a std:ostream is natural
            std::cout << "row (" << query.getColumn(0) << ", \"" << query.getColumn(1) << "\", " << query.getColumn(2) << ")\n";
        }
    }
    catch (std::exception& e)
    {
        std::cout << "SQLite exception: " << e.what() << std::endl;
    }

    ////////////////////////////////////////////////////////////////////////////
    // Object Oriented Basic example (2/6) :
    try
    {
        // Open the database and compile the query
        Example example(filename_example_db3);

        // Demonstrate the way to use the same query with different parameter values
        example.ListGreaterThan(8);
        example.ListGreaterThan(6);
        example.ListGreaterThan(2);
    }
    catch (std::exception& e)
    {
        std::cout << "SQLite exception: " << e.what() << std::endl;
    }

    // The execAndGet wrapper example (3/6) :
    try
    {
        // Open a database file in readonly mode
        SQLite::Database  db(filename_example_db3);  // SQLITE_OPEN_READONLY
        std::cout << "SQLite database file '" << db.getFilename().c_str() << "' opened successfully\n";

        // WARNING: Be very careful with this dangerous method: you have to
        // make a COPY OF THE result, else it will be destroy before the next line
        // (when the underlying temporary Statement and Column objects are destroyed)
        std::string value = db.execAndGet("SELECT value FROM test WHERE id=2");
        std::cout << "execAndGet=" << value.c_str() << std::endl;
    }
    catch (std::exception& e)
    {
        std::cout << "SQLite exception: " << e.what() << std::endl;
    }

    ////////////////////////////////////////////////////////////////////////////
    // Simple batch queries example (4/6) :
    try
    {
        // Open a database file in create/write mode
        SQLite::Database    db(testDb, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
        std::cout << "SQLite database file '" << db.getFilename().c_str() << "' opened successfully\n";

        db.exec("DROP TABLE IF EXISTS test");

        db.exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)");

        // first row
        int nb = db.exec("INSERT INTO test VALUES (NULL, \"test\")");
        std::cout << "INSERT INTO test VALUES (NULL, \"test\")\", returned " << nb << std::endl;

        // second row
        nb = db.exec("INSERT INTO test VALUES (NULL, \"second\")");
        std::cout << "INSERT INTO test VALUES (NULL, \"second\")\", returned " << nb << std::endl;

        // update the second row
        nb = db.exec("UPDATE test SET value=\"second-updated\" WHERE id='2'");
        std::cout << "UPDATE test SET value=\"second-updated\" WHERE id='2', returned " << nb << std::endl;

        // Check the results : expect two row of result
        SQLite::Statement   query(db, "SELECT * FROM test");
        std::cout << "SELECT * FROM test :\n";
        while (query.executeStep())
        {
            std::cout << "row (" << query.getColumn(0) << ", \"" << query.getColumn(1) << "\")\n";
        }

        db.exec("DROP TABLE test");
    }
    catch (std::exception& e)
    {
        std::cout << "SQLite exception: " << e.what() << std::endl;
    }

    remove(testDb.c_str());

    ////////////////////////////////////////////////////////////////////////////
    // RAII transaction example (5/6) :
    try
    {
        // Open a database file in create/write mode
        SQLite::Database db(transactionDb, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
        std::cout << "SQLite database file '" << db.getFilename().c_str() << "' opened successfully\n";

        db.exec("DROP TABLE IF EXISTS test");

        // Exemple of a successful transaction :
        try
        {
            // Begin transaction
            SQLite::Transaction transaction(db);

            db.exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)");

            int nb = db.exec("INSERT INTO test VALUES (NULL, \"test\")");
            std::cout << "INSERT INTO test VALUES (NULL, \"test\")\", returned " << nb << std::endl;

            // Commit transaction
            transaction.commit();
        }
        catch (std::exception& e)
        {
            std::cout << "SQLite exception: " << e.what() << std::endl;
        }

        // Exemple of a rollbacked transaction :
        try
        {
            // Begin transaction
            SQLite::Transaction transaction(db);

            int nb = db.exec("INSERT INTO test VALUES (NULL, \"second\")");

            std::cout << "INSERT INTO test VALUES (NULL, \"second\")\", returned " << nb << std::endl;

            nb = db.exec("INSERT INTO test ObviousError");
            std::cout << "INSERT INTO test \"error\", returned " << nb << std::endl;

            std::cout << "SQLite SHOULD EXIT: " << std::endl;

            // Commit transaction
            transaction.commit();
        }
        catch (std::exception& e)
        {
            std::cout << "SQLite exception: " << e.what() << std::endl;
            // expected error, see above
        }

        // Check the results (expect only one row of result, as the second one has been rollbacked by the error)
        SQLite::Statement   query(db, "SELECT * FROM test");
        std::cout << "SELECT * FROM test :\n";
        while (query.executeStep())
        {
            std::cout << "row (" << query.getColumn(0) << ", \"" << query.getColumn(1) << "\")\n";
        }
    }
    catch (std::exception& e)
    {
        std::cout << "SQLite exception: " << e.what() << std::endl;
    }

    remove(transactionDb.c_str());

    ////////////////////////////////////////////////////////////////////////////
    // Binary blob and in-memory database example (6/6) :
    try
    {
        // Open a database file in create/write mode
        SQLite::Database  db(":memory:", SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
        std::cout << "SQLite database file '" << db.getFilename().c_str() << "' opened successfully\n";

        db.exec("DROP TABLE IF EXISTS test");
        db.exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value BLOB)");

        FILE* fp = fopen(filename_logo_png.c_str(), "rb");
        if (NULL != fp)
        {
            char  buffer[16*1024];
            void* blob = &buffer;
            int size = static_cast<int>(fread(blob, 1, 16*1024, fp));
            buffer[size] = '\0';
            fclose (fp);
            std::cout << "blob size=" << size << " :\n";

            // Insert query
            SQLite::Statement   query(db, "INSERT INTO test VALUES (NULL, ?)");
            // Bind the blob value to the first parameter of the SQL query
            query.bind(1, blob, size);
            std::cout << "blob binded successfully\n";

            // Execute the one-step query to insert the blob
            int nb = query.exec ();
            std::cout << "INSERT INTO test VALUES (NULL, ?)\", returned " << nb << std::endl;
        }
        else
        {
            std::cout << "file " << filename_logo_png << " not found !\n";
        }

        fp = fopen(ofToDataPath("out.png", true).c_str(), "wb");
        if (NULL != fp)
        {
            const void* blob = NULL;
            size_t size;

            SQLite::Statement   query(db, "SELECT * FROM test");
            std::cout << "SELECT * FROM test :\n";
            if (query.executeStep())
            {
                SQLite::Column colBlob = query.getColumn(1);
                blob = colBlob.getBlob();
                size = colBlob.getBytes();
                std::cout << "row (" << query.getColumn(0) << ", size=" << size << ")\n";
                size_t sizew = fwrite(blob, 1, size, fp);
                SQLITECPP_ASSERT(sizew == size, "fwrite failed");   // See SQLITECPP_ENABLE_ASSERT_HANDLER
                fclose (fp);
            }
        }
        else
        {
            std::cout << "file out.png not created !\n";
        }
    }
    catch (std::exception& e)
    {
        std::cout << "SQLite exception: " << e.what() << std::endl;
    }

    remove(ofToDataPath("out.png", true).c_str());

    std::cout << "everything ok, quitting\n";

}

void ofApp::draw()
{
    ofBackgroundGradient(ofColor::white, ofColor::black);

}
<|endoftext|>


<commit_before>/*//////////////////////////////////////////////////////////////////
////       SKIRT -- an advanced radiative transfer code         ////
////       © Astronomical Observatory, Ghent University         ////
///////////////////////////////////////////////////////////////// */

#include <cmath>
#include <limits>
#include <iostream>
#include "FatalError.hpp"
#include "Random.hpp"
#include "SolarPatchGeometry.hpp"

using namespace std;

//////////////////////////////////////////////////////////////////////

SolarPatchGeometry::SolarPatchGeometry()
{
}

//////////////////////////////////////////////////////////////////////

void SolarPatchGeometry::setupSelfBefore()
{
    Geometry::setupSelfBefore();
    // verify property values
    if (_Rmax <= 0) throw FATALERROR("the patch radius Rmax should be positive");
}

//////////////////////////////////////////////////////////////////////

int SolarPatchGeometry::dimension() const
{
    return 2;
}

////////////////////////////////////////////////////////////////////

void SolarPatchGeometry::setRadius(double value)
{
    _Rmax = value;
}

////////////////////////////////////////////////////////////////////

double SolarPatchGeometry::radius() const
{
    return _Rmax;
}

//////////////////////////////////////////////////////////////////////

double SolarPatchGeometry::density(Position bfr) const
{
    if (bfr.height() != 0.0) return 0.0;
    if (bfr.cylradius() < _Rmax) return 0.0;
    return numeric_limits<double>::infinity();
}

//////////////////////////////////////////////////////////////////////

Position SolarPatchGeometry::generatePosition() const
{
    double R = _Rmax * sqrt(_random->uniform());
    double phi = 2.0*M_PI*_random->uniform();
    double z = 0.0;
    return Position(R,phi,z,Position::CYLINDRICAL);
}

//////////////////////////////////////////////////////////////////////

double SolarPatchGeometry::SigmaX() const
{
    return numeric_limits<double>::infinity();
}

//////////////////////////////////////////////////////////////////////

double SolarPatchGeometry::SigmaY() const
{
    return numeric_limits<double>::infinity();
}

//////////////////////////////////////////////////////////////////////

double SolarPatchGeometry::SigmaZ() const
{
    return 1.0/(M_PI*_Rmax*_Rmax);
}

//////////////////////////////////////////////////////////////////////

double SolarPatchGeometry::probabilityForDirection(Position /*bfr*/, Direction bfk) const
{
    double kx, ky, kz;
    bfk.cartesian(kx,ky,kz);
    return (kz > 0.0) ? 4.0*kz : 0.0;
}

//////////////////////////////////////////////////////////////////////

Direction SolarPatchGeometry::generateDirection(Position /*bfr*/) const
{
    double theta = asin(sqrt(_random->uniform()));
    double phi = 2.0*M_PI*_random->uniform();
    return Direction(theta,phi);
}

//////////////////////////////////////////////////////////////////////
<commit_msg>fix density profile of SolarPatchGeometry<commit_after>/*//////////////////////////////////////////////////////////////////
////       SKIRT -- an advanced radiative transfer code         ////
////       © Astronomical Observatory, Ghent University         ////
///////////////////////////////////////////////////////////////// */

#include <cmath>
#include <limits>
#include <iostream>
#include "FatalError.hpp"
#include "Random.hpp"
#include "SolarPatchGeometry.hpp"

using namespace std;

//////////////////////////////////////////////////////////////////////

SolarPatchGeometry::SolarPatchGeometry()
{
}

//////////////////////////////////////////////////////////////////////

void SolarPatchGeometry::setupSelfBefore()
{
    Geometry::setupSelfBefore();
    // verify property values
    if (_Rmax <= 0) throw FATALERROR("the patch radius Rmax should be positive");
}

//////////////////////////////////////////////////////////////////////

int SolarPatchGeometry::dimension() const
{
    return 2;
}

////////////////////////////////////////////////////////////////////

void SolarPatchGeometry::setRadius(double value)
{
    _Rmax = value;
}

////////////////////////////////////////////////////////////////////

double SolarPatchGeometry::radius() const
{
    return _Rmax;
}

//////////////////////////////////////////////////////////////////////

double SolarPatchGeometry::density(Position bfr) const
{
    if (bfr.height() != 0.0) return 0.0;
    if (bfr.cylradius() > _Rmax) return 0.0;
    return numeric_limits<double>::infinity();
}

//////////////////////////////////////////////////////////////////////

Position SolarPatchGeometry::generatePosition() const
{
    double R = _Rmax * sqrt(_random->uniform());
    double phi = 2.0*M_PI*_random->uniform();
    double z = 0.0;
    return Position(R,phi,z,Position::CYLINDRICAL);
}

//////////////////////////////////////////////////////////////////////

double SolarPatchGeometry::SigmaX() const
{
    return numeric_limits<double>::infinity();
}

//////////////////////////////////////////////////////////////////////

double SolarPatchGeometry::SigmaY() const
{
    return numeric_limits<double>::infinity();
}

//////////////////////////////////////////////////////////////////////

double SolarPatchGeometry::SigmaZ() const
{
    return 1.0/(M_PI*_Rmax*_Rmax);
}

//////////////////////////////////////////////////////////////////////

double SolarPatchGeometry::probabilityForDirection(Position /*bfr*/, Direction bfk) const
{
    double kx, ky, kz;
    bfk.cartesian(kx,ky,kz);
    return (kz > 0.0) ? 4.0*kz : 0.0;
}

//////////////////////////////////////////////////////////////////////

Direction SolarPatchGeometry::generateDirection(Position /*bfr*/) const
{
    double theta = asin(sqrt(_random->uniform()));
    double phi = 2.0*M_PI*_random->uniform();
    return Direction(theta,phi);
}

//////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>#include "Mesh.h"

Resources::Mesh::Mesh(Resource::RawResourceData resData, RawMeshData meshData, ID3D11Device* dev, bool keepRawData) :
	Resource(resData)
{
	this->m_resourceData.m_resType = ResourceType::RES_MESH;
	m_meshData = meshData;

	if(meshData.hasAnimation)
		this->SetVertices(meshData.m_animVertices, dev,meshData.m_numVerts,keepRawData);
	else
		this->SetVertices(meshData.m_vertices, dev, meshData.m_numVerts,keepRawData);

	SetIndices(meshData.m_indices, meshData.m_numIndices,dev,keepRawData);
}

Resources::Mesh::Mesh(Resource::RawResourceData resData)
	:Resource(resData)
{
	this->m_resourceData.m_resType = ResourceType::RES_MESH;
}

Resources::Mesh::Mesh() : Resource()
{
	m_vertBuffer	 = nullptr;
	m_AnimVertBuffer = nullptr;
	m_indexBuffer	 = nullptr;

	m_resourceData.m_resType = ResourceType::RES_MESH;

}

Resources::Mesh::Mesh(const Mesh & obj)
{
	this->m_resourceData	= obj.m_resourceData;
	this->m_meshData		= obj.m_meshData;
	this->m_vertBuffer		= obj.m_vertBuffer;
	this->m_AnimVertBuffer  = obj.m_AnimVertBuffer ;
	this->m_indexBuffer		= obj.m_indexBuffer	   ;
	this->m_boundingBox		= obj.m_boundingBox	   ;
}
Resources::Status Resources::Mesh::Create(Resource::RawResourceData * resData, ID3D11Device* dev , RawMeshData * meshData, bool keepRawData)
{
	this->Destroy();
	m_resourceData.m_id = resData->m_id;
	m_resourceData.m_resType = RES_MESH;
	if (meshData != nullptr)
	{
		if(!this->SetIndices(meshData->m_indices, meshData->m_numIndices,dev, keepRawData))
			return Status::ST_BUFFER_ERROR;
		if (meshData->hasAnimation){
			if (!SetVertices(meshData->m_animVertices,dev, meshData->m_numVerts, keepRawData))
				return Status::ST_BUFFER_ERROR;
		}
		else{
			if (!SetVertices(meshData->m_vertices,dev, meshData->m_numVerts, keepRawData)) return Status::ST_BUFFER_ERROR;
		}
		if (keepRawData == true)
		{
			m_meshData.hasAnimation = meshData->hasAnimation;
			m_meshData.m_numIndices = meshData->m_numIndices;
			m_meshData.m_numVerts   = meshData->m_numVerts;
			m_meshData.m_indices	= new unsigned int[meshData->m_numIndices];
			memcpy((char*)m_meshData.m_indices, meshData->m_indices, sizeof(unsigned int)*  meshData->m_numIndices);

			if (meshData->hasAnimation)
			{
				m_meshData.m_animVertices = new VertexAnim[meshData->m_numVerts];
				memcpy((char*)m_meshData.m_animVertices, meshData->m_animVertices, sizeof(VertexAnim)*  meshData->m_numVerts);
			}
			else
			{
				m_meshData.m_vertices = new Vertex[meshData->m_numVerts];
				memcpy((char*)m_meshData.m_vertices, meshData->m_vertices, sizeof(Vertex)*  meshData->m_numVerts);
			}
		}
	}

	return Resources::Status::ST_OK;
}

Resources::Status Resources::Mesh::Destroy()
{
	if (!EraseMeshData())
		return Status::ST_BUFFER_ERROR;
	this->m_resourceData.m_id = 0;

	return Resources::Status::ST_OK;
}

Resources::Mesh::~Mesh()
{
	EraseMeshData();
}

bool Resources::Mesh::SetVertices(Vertex * data, ID3D11Device* dev, unsigned int numVerts, bool keepRawData)
{

	delete m_meshData.m_vertices;
	m_meshData.m_vertices = nullptr;

	delete m_meshData.m_animVertices;
	m_meshData.m_animVertices = nullptr;

	if (!Resources::SAFE_RELEASE(m_AnimVertBuffer)){
		Resources::OutputErrorString(this, std::string("could not release animBuffer"));
		return false;
	}
	if (!Resources::SAFE_RELEASE(m_vertBuffer)) {
		Resources::OutputErrorString(this, std::string("could not release vertbuffer"));
		return false;
	}

	if (dev != nullptr)
	{
		D3D11_BUFFER_DESC bufferDesc;
		memset(&bufferDesc, 0, sizeof(bufferDesc));
		bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
		bufferDesc.Usage = D3D11_USAGE_DEFAULT;
		bufferDesc.ByteWidth = sizeof(Vertex)* numVerts;

		D3D11_SUBRESOURCE_DATA b_data;
		b_data.pSysMem = data;
		HRESULT hr;
		hr = dev->CreateBuffer(&bufferDesc, &b_data, &m_vertBuffer);

		if (FAILED(hr))
			return false;
	}

	if (keepRawData) {
		m_meshData.m_vertices = new Vertex[numVerts];
		memcpy(m_meshData.m_vertices,data,size_t(sizeof(Vertex)* numVerts));
		//m_meshData.m_vertices = data;
	}

	m_meshData.m_numVerts = numVerts;
	m_meshData.hasAnimation = false;

	return true;
}

bool Resources::Mesh::SetVertices(VertexAnim * data, ID3D11Device* dev, unsigned int numVerts, bool keepRawData)
{
	if (numVerts == 0)
		return false;

	delete m_meshData.m_vertices;	    m_meshData.m_vertices	  = nullptr;
	delete m_meshData.m_animVertices;	m_meshData.m_animVertices = nullptr;

	if (!Resources::SAFE_RELEASE(m_AnimVertBuffer)) {
		Resources::OutputErrorString(this, std::string("could not release animBuffer"));
		return false;
	}
	if (!Resources::SAFE_RELEASE(m_vertBuffer)) {
		Resources::OutputErrorString(this, std::string("could not release vertbuffer"));
		return false;
	}
	if (dev != nullptr){
		D3D11_BUFFER_DESC bufferDesc;
		memset(&bufferDesc, 0, sizeof(bufferDesc));
		bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
		bufferDesc.Usage = D3D11_USAGE_DEFAULT;
		bufferDesc.ByteWidth = sizeof(VertexAnim)* numVerts;

		D3D11_SUBRESOURCE_DATA b_data;
		b_data.pSysMem = data;
		HRESULT hr = S_OK;
		hr = dev->CreateBuffer(&bufferDesc, &b_data, &m_AnimVertBuffer);

		if (FAILED(hr))
			return false;
	}

	if (true)
	{
		//m_meshData.m_animVertices = data;
		m_meshData.m_animVertices = new VertexAnim[numVerts];
		memcpy(m_meshData.m_animVertices, data, size_t(sizeof(VertexAnim)* numVerts));
	}

	m_meshData.hasAnimation = true;
	m_meshData.m_numVerts = numVerts;
	return true;

}

bool Resources::Mesh::SetIndices(unsigned int * indices, unsigned int numIndices, ID3D11Device* dev, bool keepRawData)
{
	HRESULT hr = S_OK;
	Resources::SAFE_RELEASE(m_indexBuffer);

	delete m_meshData.m_indices; m_meshData.m_indices = nullptr;

	if (dev != nullptr)
	{
		D3D11_BUFFER_DESC ibd;

		ibd.Usage = D3D11_USAGE_IMMUTABLE;
		ibd.ByteWidth = sizeof(unsigned int) * numIndices;
		ibd.BindFlags = D3D11_BIND_INDEX_BUFFER;
		ibd.CPUAccessFlags = 0;
		ibd.MiscFlags = 0;
		ibd.StructureByteStride = 0;

		D3D11_SUBRESOURCE_DATA ibdData;
		ibdData.pSysMem = indices;
		hr = dev->CreateBuffer(&ibd, &ibdData, &m_indexBuffer);
		if (FAILED(hr))
			return false;
	}

	if (keepRawData)
	{
		m_meshData.m_indices = new unsigned int[numIndices];
		memcpy(m_meshData.m_indices, indices, sizeof(unsigned int)* numIndices);
	}
	m_meshData.m_numIndices = numIndices;

	return true;
}

std::shared_ptr<char> Resources::Mesh::GetDataAsBinary(size_t * size, bool * result)
{
	return std::shared_ptr<char>();
}

bool Resources::Mesh::EraseMeshData()
{
	delete m_meshData.m_animVertices;	 m_meshData.m_animVertices = nullptr;
	delete m_meshData.m_vertices;		 m_meshData.m_vertices	   = nullptr;
	delete m_meshData.m_indices;		 m_meshData.m_indices	   = nullptr;

	m_meshData.m_numVerts	= 0;
	m_meshData.m_numIndices = 0;
	m_meshData.hasAnimation = false;

	if (!Resources::SAFE_RELEASE(m_AnimVertBuffer)){
		Resources::OutputErrorString(this, std::string("could not release animBuffer")  ); return false;
	}
	if (!Resources::SAFE_RELEASE(m_vertBuffer)) {
		Resources::OutputErrorString(this, std::string("could not release vertbuffer")  ); return false;
	}
	if (!Resources::SAFE_RELEASE(m_indexBuffer)) {
		Resources::OutputErrorString(this, std::string("could not release indexbuffer")); return false;
	}

	m_AnimVertBuffer  = nullptr;
		m_vertBuffer  = nullptr;
		m_indexBuffer = nullptr;
		return true;
}

bool Resources::Mesh::SetMeshData(RawMeshData* newMeshData, ID3D11Device* dev,bool keepRawData)
{
	if (!EraseMeshData()) {
		Resources::OutputErrorString(this, std::string("could not erase MeshData"));
		return false;
	}

		m_meshData.hasAnimation = newMeshData->hasAnimation;
		m_meshData.m_numIndices = newMeshData->m_numIndices;
		m_meshData.m_numVerts   = newMeshData->m_numVerts;

	if (newMeshData->hasAnimation){
		if (!SetVertices(newMeshData->m_animVertices, dev, newMeshData->m_numVerts, keepRawData))
			return false;
	}
	else {
		if (!SetVertices(newMeshData->m_vertices, dev, newMeshData->m_numVerts,keepRawData))
			return false;
	}

	if (!SetIndices(m_meshData.m_indices, m_meshData.m_numIndices, dev, keepRawData))
		return false;

	return true;
}
<commit_msg>FIX dont save unnessesary vertex data<commit_after>#include "Mesh.h"

Resources::Mesh::Mesh(Resource::RawResourceData resData, RawMeshData meshData, ID3D11Device* dev, bool keepRawData) :
	Resource(resData)
{
	this->m_resourceData.m_resType = ResourceType::RES_MESH;
	m_meshData = meshData;

	if(meshData.hasAnimation)
		this->SetVertices(meshData.m_animVertices, dev,meshData.m_numVerts,keepRawData);
	else
		this->SetVertices(meshData.m_vertices, dev, meshData.m_numVerts,keepRawData);

	SetIndices(meshData.m_indices, meshData.m_numIndices,dev,keepRawData);
}

Resources::Mesh::Mesh(Resource::RawResourceData resData)
	:Resource(resData)
{
	this->m_resourceData.m_resType = ResourceType::RES_MESH;
}

Resources::Mesh::Mesh() : Resource()
{
	m_vertBuffer	 = nullptr;
	m_AnimVertBuffer = nullptr;
	m_indexBuffer	 = nullptr;

	m_resourceData.m_resType = ResourceType::RES_MESH;

}

Resources::Mesh::Mesh(const Mesh & obj)
{
	this->m_resourceData	= obj.m_resourceData;
	this->m_meshData		= obj.m_meshData;
	this->m_vertBuffer		= obj.m_vertBuffer;
	this->m_AnimVertBuffer  = obj.m_AnimVertBuffer ;
	this->m_indexBuffer		= obj.m_indexBuffer	   ;
	this->m_boundingBox		= obj.m_boundingBox	   ;
}
Resources::Status Resources::Mesh::Create(Resource::RawResourceData * resData, ID3D11Device* dev , RawMeshData * meshData, bool keepRawData)
{
	this->Destroy();
	m_resourceData.m_id = resData->m_id;
	m_resourceData.m_resType = RES_MESH;
	if (meshData != nullptr)
	{
		if(!this->SetIndices(meshData->m_indices, meshData->m_numIndices,dev, keepRawData))
			return Status::ST_BUFFER_ERROR;
		if (meshData->hasAnimation){
			if (!SetVertices(meshData->m_animVertices,dev, meshData->m_numVerts, keepRawData))
				return Status::ST_BUFFER_ERROR;
		}
		else{
			if (!SetVertices(meshData->m_vertices,dev, meshData->m_numVerts, keepRawData)) return Status::ST_BUFFER_ERROR;
		}
		if (keepRawData == true)
		{
			m_meshData.hasAnimation = meshData->hasAnimation;
			m_meshData.m_numIndices = meshData->m_numIndices;
			m_meshData.m_numVerts   = meshData->m_numVerts;
			m_meshData.m_indices	= new unsigned int[meshData->m_numIndices];
			memcpy((char*)m_meshData.m_indices, meshData->m_indices, sizeof(unsigned int)*  meshData->m_numIndices);

			if (meshData->hasAnimation)
			{
				m_meshData.m_animVertices = new VertexAnim[meshData->m_numVerts];
				memcpy((char*)m_meshData.m_animVertices, meshData->m_animVertices, sizeof(VertexAnim)*  meshData->m_numVerts);
			}
			else
			{
				m_meshData.m_vertices = new Vertex[meshData->m_numVerts];
				memcpy((char*)m_meshData.m_vertices, meshData->m_vertices, sizeof(Vertex)*  meshData->m_numVerts);
			}
		}
	}

	return Resources::Status::ST_OK;
}

Resources::Status Resources::Mesh::Destroy()
{
	if (!EraseMeshData())
		return Status::ST_BUFFER_ERROR;
	this->m_resourceData.m_id = 0;

	return Resources::Status::ST_OK;
}

Resources::Mesh::~Mesh()
{
	EraseMeshData();
}

bool Resources::Mesh::SetVertices(Vertex * data, ID3D11Device* dev, unsigned int numVerts, bool keepRawData)
{

	delete m_meshData.m_vertices;
	m_meshData.m_vertices = nullptr;

	delete m_meshData.m_animVertices;
	m_meshData.m_animVertices = nullptr;

	if (!Resources::SAFE_RELEASE(m_AnimVertBuffer)){
		Resources::OutputErrorString(this, std::string("could not release animBuffer"));
		return false;
	}
	if (!Resources::SAFE_RELEASE(m_vertBuffer)) {
		Resources::OutputErrorString(this, std::string("could not release vertbuffer"));
		return false;
	}

	if (dev != nullptr)
	{
		D3D11_BUFFER_DESC bufferDesc;
		memset(&bufferDesc, 0, sizeof(bufferDesc));
		bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
		bufferDesc.Usage = D3D11_USAGE_DEFAULT;
		bufferDesc.ByteWidth = sizeof(Vertex)* numVerts;

		D3D11_SUBRESOURCE_DATA b_data;
		b_data.pSysMem = data;
		HRESULT hr;
		hr = dev->CreateBuffer(&bufferDesc, &b_data, &m_vertBuffer);

		if (FAILED(hr))
			return false;
	}

	if (keepRawData) {
		m_meshData.m_vertices = new Vertex[numVerts];
		memcpy(m_meshData.m_vertices,data,size_t(sizeof(Vertex)* numVerts));
		//m_meshData.m_vertices = data;
	}

	m_meshData.m_numVerts = numVerts;
	m_meshData.hasAnimation = false;

	return true;
}

bool Resources::Mesh::SetVertices(VertexAnim * data, ID3D11Device* dev, unsigned int numVerts, bool keepRawData)
{
	if (numVerts == 0)
		return false;

	delete m_meshData.m_vertices;	    m_meshData.m_vertices	  = nullptr;
	delete m_meshData.m_animVertices;	m_meshData.m_animVertices = nullptr;

	if (!Resources::SAFE_RELEASE(m_AnimVertBuffer)) {
		Resources::OutputErrorString(this, std::string("could not release animBuffer"));
		return false;
	}
	if (!Resources::SAFE_RELEASE(m_vertBuffer)) {
		Resources::OutputErrorString(this, std::string("could not release vertbuffer"));
		return false;
	}
	if (dev != nullptr){
		D3D11_BUFFER_DESC bufferDesc;
		memset(&bufferDesc, 0, sizeof(bufferDesc));
		bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
		bufferDesc.Usage = D3D11_USAGE_DEFAULT;
		bufferDesc.ByteWidth = sizeof(VertexAnim)* numVerts;

		D3D11_SUBRESOURCE_DATA b_data;
		b_data.pSysMem = data;
		HRESULT hr = S_OK;
		hr = dev->CreateBuffer(&bufferDesc, &b_data, &m_AnimVertBuffer);

		if (FAILED(hr))
			return false;
	}

	if (keepRawData == true)
	{
		//m_meshData.m_animVertices = data;
		m_meshData.m_animVertices = new VertexAnim[numVerts];
		memcpy(m_meshData.m_animVertices, data, size_t(sizeof(VertexAnim)* numVerts));
	}

	m_meshData.hasAnimation = true;
	m_meshData.m_numVerts = numVerts;
	return true;

}

bool Resources::Mesh::SetIndices(unsigned int * indices, unsigned int numIndices, ID3D11Device* dev, bool keepRawData)
{
	HRESULT hr = S_OK;
	Resources::SAFE_RELEASE(m_indexBuffer);

	delete m_meshData.m_indices; m_meshData.m_indices = nullptr;

	if (dev != nullptr)
	{
		D3D11_BUFFER_DESC ibd;

		ibd.Usage = D3D11_USAGE_IMMUTABLE;
		ibd.ByteWidth = sizeof(unsigned int) * numIndices;
		ibd.BindFlags = D3D11_BIND_INDEX_BUFFER;
		ibd.CPUAccessFlags = 0;
		ibd.MiscFlags = 0;
		ibd.StructureByteStride = 0;

		D3D11_SUBRESOURCE_DATA ibdData;
		ibdData.pSysMem = indices;
		hr = dev->CreateBuffer(&ibd, &ibdData, &m_indexBuffer);
		if (FAILED(hr))
			return false;
	}

	if (keepRawData)
	{
		m_meshData.m_indices = new unsigned int[numIndices];
		memcpy(m_meshData.m_indices, indices, sizeof(unsigned int)* numIndices);
	}
	m_meshData.m_numIndices = numIndices;

	return true;
}

std::shared_ptr<char> Resources::Mesh::GetDataAsBinary(size_t * size, bool * result)
{
	return std::shared_ptr<char>();
}

bool Resources::Mesh::EraseMeshData()
{
	delete m_meshData.m_animVertices;	 m_meshData.m_animVertices = nullptr;
	delete m_meshData.m_vertices;		 m_meshData.m_vertices	   = nullptr;
	delete m_meshData.m_indices;		 m_meshData.m_indices	   = nullptr;

	m_meshData.m_numVerts	= 0;
	m_meshData.m_numIndices = 0;
	m_meshData.hasAnimation = false;

	if (!Resources::SAFE_RELEASE(m_AnimVertBuffer)){
		Resources::OutputErrorString(this, std::string("could not release animBuffer")  ); return false;
	}
	if (!Resources::SAFE_RELEASE(m_vertBuffer)) {
		Resources::OutputErrorString(this, std::string("could not release vertbuffer")  ); return false;
	}
	if (!Resources::SAFE_RELEASE(m_indexBuffer)) {
		Resources::OutputErrorString(this, std::string("could not release indexbuffer")); return false;
	}

	m_AnimVertBuffer  = nullptr;
		m_vertBuffer  = nullptr;
		m_indexBuffer = nullptr;
		return true;
}

bool Resources::Mesh::SetMeshData(RawMeshData* newMeshData, ID3D11Device* dev,bool keepRawData)
{
	if (!EraseMeshData()) {
		Resources::OutputErrorString(this, std::string("could not erase MeshData"));
		return false;
	}

		m_meshData.hasAnimation = newMeshData->hasAnimation;
		m_meshData.m_numIndices = newMeshData->m_numIndices;
		m_meshData.m_numVerts   = newMeshData->m_numVerts;

	if (newMeshData->hasAnimation){
		if (!SetVertices(newMeshData->m_animVertices, dev, newMeshData->m_numVerts, keepRawData))
			return false;
	}
	else {
		if (!SetVertices(newMeshData->m_vertices, dev, newMeshData->m_numVerts,keepRawData))
			return false;
	}

	if (!SetIndices(m_meshData.m_indices, m_meshData.m_numIndices, dev, keepRawData))
		return false;

	return true;
}
<|endoftext|>


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

/* $Id$ */

//-------------------------------------------------------------------------
//     Event handler for AOD input
//     Author: Andreas Morsch, CERN
//-------------------------------------------------------------------------

#include <TSystem.h>
#include <TTree.h>
#include <TList.h>
#include <TNamed.h>
#include <TFile.h>
#include <TH2.h>

#include "AliAODInputHandler.h"
#include "AliAODEvent.h"
#include "AliVCuts.h"
#include "AliMCEvent.h"
#include "AliAODpidUtil.h"

ClassImp(AliAODInputHandler)

static Option_t *gAODDataType = "AOD";

//______________________________________________________________________________
AliAODInputHandler::AliAODInputHandler() :
    AliInputEventHandler(),
    fEvent(0),
    fMCEvent(0),
    fFriends(0),
    fAODpidUtil(0x0),
    fMergeEvents(kFALSE),
    fMergeTracks(kTRUE),
    fMergeEMCALClusters(kTRUE),
    fMergePHOSClusters(kTRUE),
    fMergeEMCALCells(kTRUE),
	fMergePHOSCells(kTRUE),
	fMergeEMCALTrigger(kTRUE),
	fMergePHOSTrigger(kTRUE),
   fMergeHMPIDrings(kTRUE),
    fFriendsConnected(kFALSE),
    fFileToMerge(0),
    fTreeToMerge(0),
    fAODEventToMerge(0),
    fMergeOffset(0)
{
  // Default constructor
  fHistStatistics[0] = fHistStatistics[1] = NULL;
}

//______________________________________________________________________________
AliAODInputHandler::AliAODInputHandler(const char* name, const char* title):
  AliInputEventHandler(name, title),
  fEvent(0),
  fMCEvent(new AliMCEvent()),
  fFriends(new TList()),
  fAODpidUtil(0x0),
  fMergeEvents(kFALSE),
  fMergeTracks(kTRUE),
  fMergeEMCALClusters(kTRUE),
  fMergePHOSClusters(kTRUE),
  fMergeEMCALCells(kTRUE),
  fMergePHOSCells(kTRUE),
  fMergeEMCALTrigger(kTRUE),
  fMergePHOSTrigger(kTRUE),
  fMergeHMPIDrings(kTRUE),
  fFriendsConnected(kFALSE),
  fFileToMerge(0),
  fTreeToMerge(0),
  fAODEventToMerge(0),
  fMergeOffset(0)
{
    // Constructor
  fHistStatistics[0] = fHistStatistics[1] = NULL;
}

//______________________________________________________________________________
AliAODInputHandler::~AliAODInputHandler()
{
// Destructor
  if (fFriends) fFriends->Delete();
  delete fFriends;
  delete fHistStatistics[0];
  delete fHistStatistics[1];
  delete fAODpidUtil;
}

//______________________________________________________________________________
Bool_t AliAODInputHandler::Init(TTree* tree, Option_t* opt)
{
    // Initialisation necessary for each new tree
    fTree = tree;
    if (!fTree) return kFALSE;
    fTree->GetEntries();
    ConnectFriends();

    SwitchOffBranches();
    SwitchOnBranches();

    // Get pointer to AOD event
    if (!fEvent) fEvent = new AliAODEvent();

    fEvent->ReadFromTree(fTree);

    if (fMixingHandler) fMixingHandler->Init(tree, opt);

    return kTRUE;
}

//______________________________________________________________________________
Bool_t AliAODInputHandler::BeginEvent(Long64_t entry)
{
    // Begin event
    TClonesArray* mcParticles = (TClonesArray*) (fEvent->FindListObject("mcparticles"));
    if (mcParticles) {
       if (!fMCEvent) fMCEvent = new AliMCEvent();
       fMCEvent->SetParticleArray(mcParticles);
    }
    // When merging, get current event number from GetReadEntry(),
    // entry gives the events in the current file
    if (fTreeToMerge) fTreeToMerge->GetEntry(GetReadEntry() + fMergeOffset);

    if (fEventCuts)
      fIsSelectedResult = fEventCuts->GetSelectionMask(fEvent);
    else
      fIsSelectedResult = fEvent->GetHeader()->GetOfflineTrigger();

    if (fMixingHandler) fMixingHandler->BeginEvent(entry);

    return kTRUE;
}

//______________________________________________________________________________
Bool_t AliAODInputHandler::Notify(const char* path)
{
  // Notifaction of directory change
  if (fMixingHandler) fMixingHandler->Notify(path);
  if (!fFriendsConnected) {
      ConnectFriends();
      fEvent->ReadFromTree(fTree, "reconnect");
  }
  fFriendsConnected = kFALSE;
  fUserInfo=fTree->GetTree()->GetUserInfo();

  TTree *ttree = fTree->GetTree();
  if (!ttree) ttree = fTree;
  TString statFname(ttree->GetCurrentFile()->GetName());
  AliInfo(Form("Moving to file %s", statFname.Data()));
  Int_t indarchive = statFname.Index("#");
  if (indarchive<0) {
     statFname = gSystem->DirName(statFname);
     statFname += "/";
  } else {
     statFname.Remove(indarchive+1);
  }
  statFname += "EventStat_temp.root";
  TFile *statFile = 0;
  if (IsCheckStatistics()) statFile = TFile::Open(statFname, "READ");
  if (statFile) {
     TList *list = (TList*)statFile->Get("cstatsout");
     if (list) {
        AliVCuts *physSel = (AliVCuts*)list->At(0);
        if (physSel) {
           TH2F *hAll = dynamic_cast<TH2F*>(physSel->GetStatistics("ALL"));
           TH2F *hBin0 = dynamic_cast<TH2F*>(physSel->GetStatistics("BIN0"));
           if (fHistStatistics[0] && hAll) {
              TList tmplist;
              tmplist.Add(hAll);
              fHistStatistics[0]->Merge(&tmplist);
              tmplist.Clear();
              tmplist.Add(hBin0);
              if (fHistStatistics[1] && hBin0) fHistStatistics[1]->Merge(&tmplist);
           } else {
             if (hAll && hBin0) {
                fHistStatistics[0] = static_cast<TH2F*>(hAll->Clone());
                fHistStatistics[1] = static_cast<TH2F*>(hBin0->Clone());
                fHistStatistics[0]->SetDirectory(0);
                fHistStatistics[1]->SetDirectory(0);
             }
           }
        }
        delete list;
     }
     delete statFile;
  }
  return kTRUE;
}

//______________________________________________________________________________
Bool_t AliAODInputHandler::FinishEvent()
{
  // Finish event
  if (fMixingHandler) fMixingHandler->FinishEvent();
  if (fEvent) fEvent->Reset();
  return kTRUE;
}

//______________________________________________________________________________
void AliAODInputHandler::AddFriend(char* filename)
{
    // Add a friend tree
    TNamed* obj = new TNamed(filename, filename);
    if (!fFriends) fFriends = new TList();
    fFriends->Add(obj);
}

//______________________________________________________________________________
Option_t *AliAODInputHandler::GetDataType() const
{
// Returns handled data type.
   return gAODDataType;
}

//______________________________________________________________________________
TObject *AliAODInputHandler::GetStatistics(Option_t *option) const
{
// Get the statistics histogram(s) from the physics selection object. This
// should be called during FinishTaskOutput(). Option can be empty (default
// statistics histogram) or BIN0.
   TString opt(option);
   opt.ToUpper();
   if (opt=="BIN0") return fHistStatistics[1];
   return fHistStatistics[0];
}

void AliAODInputHandler::ConnectFriends()
{
    // Connect the friend trees
    if (!fFriends) return;
    if (!fMergeEvents) {
	TIter next(fFriends);
	TNamed* obj;
	TString aodTreeFName,aodFriendTreeFName;
	TTree *ttree = fTree->GetTree();
	if (!ttree) ttree = fTree;
	aodTreeFName = ttree->GetCurrentFile()->GetName();

	while((obj = (TNamed*)next())) {
	    aodFriendTreeFName = aodTreeFName;
       if (strlen(GetInputFileName())) aodFriendTreeFName.ReplaceAll(GetInputFileName(),obj->GetName());
	    aodFriendTreeFName.ReplaceAll("AliAOD.root",obj->GetName());
	    aodFriendTreeFName.ReplaceAll("AliAODs.root",obj->GetName());
	    ttree->AddFriend("aodTree", aodFriendTreeFName.Data());
	}
    } else {
	// Friends have to be merged
	TNamed* filename = (TNamed*) (fFriends->At(0));
        fFileToMerge = TFile::Open(filename->GetName());
	if (fFileToMerge) {
	    fFileToMerge->GetObject("aodTree", fTreeToMerge);
	    if (!fAODEventToMerge) fAODEventToMerge = new AliAODEvent();
	    fAODEventToMerge->ReadFromTree(fTreeToMerge);
	}
    }
    fFriendsConnected = kTRUE;
}

//______________________________________________________________________________
void AliAODInputHandler::CreatePIDResponse(Bool_t isMC/*=kFALSE*/)
{
  //
  // create the pid response object if it does not exist yet
  //
  if (fAODpidUtil) return;
  fAODpidUtil=new AliAODpidUtil(isMC);

}

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

/* $Id$ */

//-------------------------------------------------------------------------
//     Event handler for AOD input
//     Author: Andreas Morsch, CERN
//-------------------------------------------------------------------------

#include <TSystem.h>
#include <TTree.h>
#include <TList.h>
#include <TNamed.h>
#include <TFile.h>
#include <TH2.h>

#include "AliAODInputHandler.h"
#include "AliAODEvent.h"
#include "AliVCuts.h"
#include "AliMCEvent.h"
#include "AliAODpidUtil.h"

ClassImp(AliAODInputHandler)

static Option_t *gAODDataType = "AOD";

//______________________________________________________________________________
AliAODInputHandler::AliAODInputHandler() :
    AliInputEventHandler(),
    fEvent(0),
    fMCEvent(0),
    fFriends(0),
    fAODpidUtil(0x0),
    fMergeEvents(kFALSE),
    fMergeTracks(kTRUE),
    fMergeEMCALClusters(kTRUE),
    fMergePHOSClusters(kTRUE),
    fMergeEMCALCells(kTRUE),
	fMergePHOSCells(kTRUE),
	fMergeEMCALTrigger(kTRUE),
	fMergePHOSTrigger(kTRUE),
   fMergeHMPIDrings(kTRUE),
    fFriendsConnected(kFALSE),
    fFileToMerge(0),
    fTreeToMerge(0),
    fAODEventToMerge(0),
    fMergeOffset(0)
{
  // Default constructor
  fHistStatistics[0] = fHistStatistics[1] = NULL;
}

//______________________________________________________________________________
AliAODInputHandler::AliAODInputHandler(const char* name, const char* title):
  AliInputEventHandler(name, title),
  fEvent(0),
  fMCEvent(new AliMCEvent()),
  fFriends(new TList()),
  fAODpidUtil(0x0),
  fMergeEvents(kFALSE),
  fMergeTracks(kTRUE),
  fMergeEMCALClusters(kTRUE),
  fMergePHOSClusters(kTRUE),
  fMergeEMCALCells(kTRUE),
  fMergePHOSCells(kTRUE),
  fMergeEMCALTrigger(kTRUE),
  fMergePHOSTrigger(kTRUE),
  fMergeHMPIDrings(kTRUE),
  fFriendsConnected(kFALSE),
  fFileToMerge(0),
  fTreeToMerge(0),
  fAODEventToMerge(0),
  fMergeOffset(0)
{
    // Constructor
  fHistStatistics[0] = fHistStatistics[1] = NULL;
}

//______________________________________________________________________________
AliAODInputHandler::~AliAODInputHandler()
{
// Destructor
  if (fFriends) fFriends->Delete();
  delete fFriends;
  delete fHistStatistics[0];
  delete fHistStatistics[1];
  delete fAODpidUtil;
}

//______________________________________________________________________________
Bool_t AliAODInputHandler::Init(TTree* tree, Option_t* opt)
{
    // Initialisation necessary for each new tree
    fTree = tree;
    if (!fTree) return kFALSE;
    fTree->GetEntries();
    ConnectFriends();

    SwitchOffBranches();
    SwitchOnBranches();

    // Get pointer to AOD event
    if (!fEvent) fEvent = new AliAODEvent();

    fEvent->ReadFromTree(fTree);

    if (fMixingHandler) fMixingHandler->Init(tree, opt);

    return kTRUE;
}

//______________________________________________________________________________
Bool_t AliAODInputHandler::BeginEvent(Long64_t entry)
{
    // Begin event
    TClonesArray* mcParticles = (TClonesArray*) (fEvent->FindListObject("mcparticles"));
    if (mcParticles) {
       if (!fMCEvent) fMCEvent = new AliMCEvent();
       fMCEvent->SetParticleArray(mcParticles);
    }
    // When merging, get current event number from GetReadEntry(),
    // entry gives the events in the current file
    if (fTreeToMerge) fTreeToMerge->GetEntry(GetReadEntry() + fMergeOffset);

    if (fEventCuts)
      fIsSelectedResult = fEventCuts->GetSelectionMask(fEvent);
    else
      fIsSelectedResult = fEvent->GetHeader()->GetOfflineTrigger();

    if (fMixingHandler) fMixingHandler->BeginEvent(entry);

    return kTRUE;
}

//______________________________________________________________________________
Bool_t AliAODInputHandler::Notify(const char* path)
{
  // Notifaction of directory change
  if (fMixingHandler) fMixingHandler->Notify(path);
  if (!fFriendsConnected) {
      ConnectFriends();
      fEvent->ReadFromTree(fTree, "reconnect");
  }
  fFriendsConnected = kFALSE;
  fUserInfo=fTree->GetTree()->GetUserInfo();

  TTree *ttree = fTree->GetTree();
  if (!ttree) ttree = fTree;
  TString statFname(ttree->GetCurrentFile()->GetName());
  AliInfo(Form("Moving to file %s", statFname.Data()));
  Int_t indarchive = statFname.Index("#");
  if (indarchive<0) {
     statFname = gSystem->DirName(statFname);
     statFname += "/";
  } else {
     statFname.Remove(indarchive+1);
  }
  statFname += "EventStat_temp.root";
  TFile *statFile = 0;
  if (IsCheckStatistics()) statFile = TFile::Open(statFname, "READ");
  if (statFile) {
     TList *list = (TList*)statFile->Get("cstatsout");
     if (list) {
        AliVCuts *physSel = (AliVCuts*)list->At(0);
        if (physSel) {
           TH2F *hAll = dynamic_cast<TH2F*>(physSel->GetStatistics("ALL"));
           TH2F *hBin0 = dynamic_cast<TH2F*>(physSel->GetStatistics("BIN0"));
           if (fHistStatistics[0] && hAll) {
              TList tmplist;
              tmplist.Add(hAll);
              fHistStatistics[0]->Merge(&tmplist);
              tmplist.Clear();
              tmplist.Add(hBin0);
              if (fHistStatistics[1] && hBin0) fHistStatistics[1]->Merge(&tmplist);
           } else {
             if (hAll && hBin0) {
                fHistStatistics[0] = static_cast<TH2F*>(hAll->Clone());
                fHistStatistics[1] = static_cast<TH2F*>(hBin0->Clone());
                fHistStatistics[0]->SetDirectory(0);
                fHistStatistics[1]->SetDirectory(0);
             }
           }
        }
        delete list;
     }
     delete statFile;
  }
  return kTRUE;
}

//______________________________________________________________________________
Bool_t AliAODInputHandler::FinishEvent()
{
  // Finish event
  if (fMixingHandler) fMixingHandler->FinishEvent();
  if (fEvent) fEvent->Reset();
  return kTRUE;
}

//______________________________________________________________________________
void AliAODInputHandler::AddFriend(char* filename)
{
    // Add a friend tree
    TNamed* obj = new TNamed(filename, filename);
    if (!fFriends) fFriends = new TList();
    fFriends->Add(obj);
}

//______________________________________________________________________________
Option_t *AliAODInputHandler::GetDataType() const
{
// Returns handled data type.
   return gAODDataType;
}

//______________________________________________________________________________
TObject *AliAODInputHandler::GetStatistics(Option_t *option) const
{
// Get the statistics histogram(s) from the physics selection object. This
// should be called during FinishTaskOutput(). Option can be empty (default
// statistics histogram) or BIN0.
   TString opt(option);
   opt.ToUpper();
   if (opt=="BIN0") return fHistStatistics[1];
   return fHistStatistics[0];
}

void AliAODInputHandler::ConnectFriends()
{
    // Connect the friend trees
    if (!fFriends) return;
    if (!fMergeEvents) {
	TIter next(fFriends);
	TNamed* obj;
	TString aodTreeFName,aodFriendTreeFName;
	TTree *ttree = fTree->GetTree();
	if (!ttree) ttree = fTree;
   if(!ttree->GetCurrentFile()){
     AliWarning("Couldn't get current AOD file, not connecting friends");
     return;
   }
	aodTreeFName = ttree->GetCurrentFile()->GetName();

	while((obj = (TNamed*)next())) {
	    aodFriendTreeFName = aodTreeFName;
       if (strlen(GetInputFileName())) aodFriendTreeFName.ReplaceAll(GetInputFileName(),obj->GetName());
	    aodFriendTreeFName.ReplaceAll("AliAOD.root",obj->GetName());
	    aodFriendTreeFName.ReplaceAll("AliAODs.root",obj->GetName());
	    ttree->AddFriend("aodTree", aodFriendTreeFName.Data());
	}
    } else {
	// Friends have to be merged
	TNamed* filename = (TNamed*) (fFriends->At(0));
        fFileToMerge = TFile::Open(filename->GetName());
	if (fFileToMerge) {
	    fFileToMerge->GetObject("aodTree", fTreeToMerge);
	    if (!fAODEventToMerge) fAODEventToMerge = new AliAODEvent();
	    fAODEventToMerge->ReadFromTree(fTreeToMerge);
	}
    }
    fFriendsConnected = kTRUE;
}

//______________________________________________________________________________
void AliAODInputHandler::CreatePIDResponse(Bool_t isMC/*=kFALSE*/)
{
  //
  // create the pid response object if it does not exist yet
  //
  if (fAODpidUtil) return;
  fAODpidUtil=new AliAODpidUtil(isMC);

}

<|endoftext|>