<commit_before>/*
   Copyright (c) 2012-1015 Alex Zhondin <qtinuum.team@gmail.com>

   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 "PropertyDelegateQFont.h"
#include "../../../Core/GUI/PropertyQFont.h"
#include "../../../Core/Core/PropertyQString.h"
#include "../../../Core/Core/PropertyUInt.h"
#include "../../../Core/Core/PropertyBool.h"
#include "../../../Core/Core/PropertyEnum.h"
#include "../PropertyDelegateFactory.h"
#include "../PropertyEditorHandler.h"
#include "../PropertyEditorAux.h"

#include <QFontDialog>
#include <QFontDatabase>

static QString FontToStr(const QFont &font)
{
	int size = font.pointSize();
	bool pixels = (size < 0);
	if (pixels)
		size = font.pixelSize();

	return QString("[%1, %2 %3]").arg(font.family(), QString::number(size), QString(pixels ? "px" : "pt"));
}

class QtnPropertyQFontLineEditBttnHandler
		: public QtnPropertyEditorBttnHandler<QtnPropertyQFontBase, QtnLineEditBttn>
{
public:
    QtnPropertyQFontLineEditBttnHandler(QtnPropertyQFontBase& property, QtnLineEditBttn& editor)
        : QtnPropertyEditorHandlerType(property, editor)
    {
        editor.lineEdit->setReadOnly(true);

        if (!property.isEditableByUser())
        {
//            editor.lineEdit->setReadOnly(true);
            editor.toolButton->setEnabled(false);
        }

        updateEditor();
		editor.lineEdit->installEventFilter(this);
		QObject::connect(editor.toolButton, &QToolButton::clicked,
						 this, &QtnPropertyQFontLineEditBttnHandler::onToolButtonClicked);
    }

protected:
	virtual void onToolButtonClick() override { onToolButtonClicked(false); }
	virtual void updateEditor() override
    {
		editor().lineEdit->setText(FontToStr(property()));
    }

private:
	void onToolButtonClicked(bool)
    {
        QFontDialog dlg(property(), &editor());
        if (dlg.exec() == QDialog::Accepted)
        {
            property() = dlg.currentFont();
        }
    }
};

static bool regQFontDelegate = QtnPropertyDelegateFactory::staticInstance()
                                .registerDelegateDefault(&QtnPropertyQFontBase::staticMetaObject
                                , &qtnCreateDelegate<QtnPropertyDelegateQFont, QtnPropertyQFontBase>
                                , "LineEditBttn");

static QtnEnumInfo* styleStrategyEnum()
{
    static QtnEnumInfo* enumInfo = nullptr;
    if (!enumInfo)
    {
        QVector<QtnEnumValueInfo> items;
		items.append(QtnEnumValueInfo(QFont::PreferDefault, QtnPropertyQFont::getPreferDefaultStr()));
		items.append(QtnEnumValueInfo(QFont::NoAntialias, QtnPropertyQFont::getNoAntialiasStr()));
		items.append(QtnEnumValueInfo(QFont::PreferAntialias, QtnPropertyQFont::getPreferAntialiasStr()));
		enumInfo = new QtnEnumInfo("FontStyleStrategy", items);
    }

    return enumInfo;
}

enum
{
	SizeUnitPixel,
	SizeUnitPoint
};

static QtnEnumInfo* sizeUnitEnum()
{
	static QtnEnumInfo* enumInfo = nullptr;
	if (!enumInfo)
	{
		QVector<QtnEnumValueInfo> items;
		items.append(QtnEnumValueInfo(SizeUnitPixel, QtnPropertyQFont::getPixelStr()));
		items.append(QtnEnumValueInfo(SizeUnitPoint, QtnPropertyQFont::getPointStr()));
		enumInfo = new QtnEnumInfo("FontSizeUnit", items);
	}

	return enumInfo;
}

QtnPropertyDelegateQFont::QtnPropertyDelegateQFont(QtnPropertyQFontBase& owner)
    : QtnPropertyDelegateTypedEx<QtnPropertyQFontBase>(owner)
{
    QtnPropertyQStringCallback* propertyFamily = new QtnPropertyQStringCallback(0);
    addSubProperty(propertyFamily);
	propertyFamily->setName(QtnPropertyQFont::getFamilyLabel());
	propertyFamily->setDescription(QtnPropertyQFont::getFamilyDescription(owner.name()));
    propertyFamily->setCallbackValueGet([&owner]()->QString {
        return owner.value().family();
    });
    propertyFamily->setCallbackValueSet([&owner](QString value) {
        QFont font = owner.value();
        font.setFamily(value);
        owner.setValue(font);
    });
    QtnPropertyDelegateInfo delegate;
    delegate.name = "List";
    QFontDatabase fDB;
    delegate.attributes["items"] = fDB.families();
    propertyFamily->setDelegate(delegate);

	QtnPropertyUIntCallback* propertySize = new QtnPropertyUIntCallback(0);
	addSubProperty(propertySize);
	propertySize->setName(QtnPropertyQFont::getSizeLabel());
	propertySize->setDescription(QtnPropertyQFont::getSizeDescription(owner.name()));
	propertySize->setCallbackValueGet([&owner]() -> quint32
	{
        int ps = owner.value().pointSize();
		if (ps < 0)
			ps = owner.value().pixelSize();
		if (ps < 1)
			ps = 1;
		return ps;
    });
	propertySize->setCallbackValueSet([&owner](quint32 value)
	{
		if (value == 0)
			value = 1;

        QFont font = owner.value();
		if (font.pointSize() > 0)
		{
			if (value > 128)
				value = 128;

			font.setPointSize((int) value);
		} else
		{
			if (value > 256)
				value = 256;

			font.setPixelSize((int) value);
		}
        owner.setValue(font);
    });

	QtnPropertyEnumCallback* propertySizeUnit = new QtnPropertyEnumCallback(0);
	addSubProperty(propertySizeUnit);
	propertySizeUnit->setName(QtnPropertyQFont::getSizeUnitLabel());
	propertySizeUnit->setDescription(QtnPropertyQFont::getSizeUnitDescription(owner.name()));
	propertySizeUnit->setEnumInfo(sizeUnitEnum());
	propertySizeUnit->setCallbackValueGet([&owner]() -> QtnEnumValueType
	{
		if (owner.value().pointSize() < 0)
			return SizeUnitPixel;

		return SizeUnitPoint;
	});
	propertySizeUnit->setCallbackValueSet([&owner](QtnEnumValueType value)
	{
		QFont font = owner.value();

		int size = std::max(font.pointSize(), font.pixelSize());

		switch (value)
		{
			case SizeUnitPixel:
				font.setPixelSize(size);
				break;

			case SizeUnitPoint:
				font.setPointSize(size);
				break;

			default:
				break;
		}

		owner.setValue(font);
	});

    QtnPropertyBoolCallback* propertyBold = new QtnPropertyBoolCallback(0);
    addSubProperty(propertyBold);
	propertyBold->setName(QtnPropertyQFont::getBoldLabel());
	propertyBold->setDescription(QtnPropertyQFont::getBoldDescription(owner.name()));
    propertyBold->setCallbackValueGet([&owner]()->bool {
        return owner.value().bold();
    });
    propertyBold->setCallbackValueSet([&owner](bool value) {
        QFont font = owner.value();
        font.setBold(value);
        owner.setValue(font);
    });

    QtnPropertyBoolCallback* propertyItalic = new QtnPropertyBoolCallback(0);
    addSubProperty(propertyItalic);
	propertyItalic->setName(QtnPropertyQFont::getItalicLabel());
	propertyItalic->setDescription(QtnPropertyQFont::getItalicDescription(owner.name()));
    propertyItalic->setCallbackValueGet([&owner]()->bool {
        return owner.value().italic();
    });
    propertyItalic->setCallbackValueSet([&owner](bool value) {
        QFont font = owner.value();
        font.setItalic(value);
        owner.setValue(font);
    });

    QtnPropertyBoolCallback* propertyUnderline = new QtnPropertyBoolCallback(0);
    addSubProperty(propertyUnderline);
	propertyUnderline->setName(QtnPropertyQFont::getUnderlineLabel());
	propertyUnderline->setDescription(QtnPropertyQFont::getUnderlineDescription(owner.name()));
    propertyUnderline->setCallbackValueGet([&owner]()->bool {
        return owner.value().underline();
    });
    propertyUnderline->setCallbackValueSet([&owner](bool value) {
        QFont font = owner.value();
        font.setUnderline(value);
        owner.setValue(font);
    });

    QtnPropertyBoolCallback* propertyStrikeout = new QtnPropertyBoolCallback(0);
    addSubProperty(propertyStrikeout);
	propertyStrikeout->setName(QtnPropertyQFont::getStrikeoutLabel());
	propertyStrikeout->setDescription(QtnPropertyQFont::getStrikeoutDescription(owner.name()));
    propertyStrikeout->setCallbackValueGet([&owner]()->bool {
        return owner.value().strikeOut();
    });
    propertyStrikeout->setCallbackValueSet([&owner](bool value) {
        QFont font = owner.value();
        font.setStrikeOut(value);
        owner.setValue(font);
    });

    QtnPropertyBoolCallback* propertyKerning = new QtnPropertyBoolCallback(0);
    addSubProperty(propertyKerning);
	propertyKerning->setName(QtnPropertyQFont::getKerningLabel());
	propertyKerning->setDescription(QtnPropertyQFont::getKerningDescription(owner.name()));
    propertyKerning->setCallbackValueGet([&owner]()->bool {
        return owner.value().kerning();
    });
    propertyKerning->setCallbackValueSet([&owner](bool value) {
        QFont font = owner.value();
        font.setKerning(value);
        owner.setValue(font);
    });

    QtnPropertyEnumCallback* propertyAntialiasing = new QtnPropertyEnumCallback(0);
    addSubProperty(propertyAntialiasing);
	propertyAntialiasing->setName(QtnPropertyQFont::getAntialiasingLabel());
	propertyAntialiasing->setDescription(QtnPropertyQFont::getAntialiasingDescription(owner.name()));
    propertyAntialiasing->setEnumInfo(styleStrategyEnum());
    propertyAntialiasing->setCallbackValueGet([&owner]()->QtnEnumValueType {
        return owner.value().styleStrategy();
    });
    propertyAntialiasing->setCallbackValueSet([&owner](QtnEnumValueType value) {
        QFont font = owner.value();
        font.setStyleStrategy((QFont::StyleStrategy)value);
        owner.setValue(font);
    });
}

void QtnPropertyDelegateQFont::drawValueImpl(QStylePainter& painter, const QRect& rect, const QStyle::State& state, bool* needTooltip) const
{
    QFont value = owner().value();

    QRect textRect = rect;

    if (textRect.isValid())
    {
        QRect br;

        QFont oldFont = painter.font();
        QFont newFont(value);
        newFont.setPointSize(oldFont.pointSize());
        painter.setFont(newFont);
        painter.drawText(textRect, Qt::AlignLeading | Qt::AlignVCenter, "A", &br);
        painter.setFont(oldFont);

        textRect.setLeft(br.right() + 3);
    }

    if (textRect.isValid())
    {
        QtnPropertyDelegateTypedEx<QtnPropertyQFontBase>::drawValueImpl(painter, textRect, state, needTooltip);
    }
}

QWidget* QtnPropertyDelegateQFont::createValueEditorImpl(QWidget* parent, const QRect& rect, QtnInplaceInfo* inplaceInfo)
{
    QtnLineEditBttn* editor = new QtnLineEditBttn(parent);
    editor->setGeometry(rect);

    new QtnPropertyQFontLineEditBttnHandler(owner(), *editor);

    if (inplaceInfo)
    {
        editor->lineEdit->selectAll();
    }

    return editor;
}

bool QtnPropertyDelegateQFont::propertyValueToStr(QString& strValue) const
{
	strValue = FontToStr(owner().value());
    return true;
}
<commit_msg>Select font size in pixels<commit_after>/*
   Copyright (c) 2012-1015 Alex Zhondin <qtinuum.team@gmail.com>

   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 "PropertyDelegateQFont.h"
#include "../../../Core/GUI/PropertyQFont.h"
#include "../../../Core/Core/PropertyQString.h"
#include "../../../Core/Core/PropertyUInt.h"
#include "../../../Core/Core/PropertyBool.h"
#include "../../../Core/Core/PropertyEnum.h"
#include "../PropertyDelegateFactory.h"
#include "../PropertyEditorHandler.h"
#include "../PropertyEditorAux.h"

#include <QFontDialog>
#include <QFontDatabase>

static QString FontToStr(const QFont &font)
{
	int size = font.pointSize();
	bool pixels = (size < 0);
	if (pixels)
		size = font.pixelSize();

	return QString("[%1, %2 %3]").arg(font.family(), QString::number(size), QString(pixels ? "px" : "pt"));
}

class QtnPropertyQFontLineEditBttnHandler
		: public QtnPropertyEditorBttnHandler<QtnPropertyQFontBase, QtnLineEditBttn>
{
public:
    QtnPropertyQFontLineEditBttnHandler(QtnPropertyQFontBase& property, QtnLineEditBttn& editor)
        : QtnPropertyEditorHandlerType(property, editor)
    {
        editor.lineEdit->setReadOnly(true);

        if (!property.isEditableByUser())
        {
//            editor.lineEdit->setReadOnly(true);
            editor.toolButton->setEnabled(false);
        }

        updateEditor();
		editor.lineEdit->installEventFilter(this);
		QObject::connect(editor.toolButton, &QToolButton::clicked,
						 this, &QtnPropertyQFontLineEditBttnHandler::onToolButtonClicked);
    }

protected:
	virtual void onToolButtonClick() override { onToolButtonClicked(false); }
	virtual void updateEditor() override
    {
		editor().lineEdit->setText(FontToStr(property()));
    }

private:
	void onToolButtonClicked(bool)
    {
        QFontDialog dlg(property(), &editor());
        if (dlg.exec() == QDialog::Accepted)
        {
			auto font = property().value();
			int pixel_size = font.pixelSize();
			font = dlg.currentFont();

			if (pixel_size > 0)
				font.setPixelSize(font.pointSize());

			property().setValue(font);
        }
    }
};

static bool regQFontDelegate = QtnPropertyDelegateFactory::staticInstance()
                                .registerDelegateDefault(&QtnPropertyQFontBase::staticMetaObject
                                , &qtnCreateDelegate<QtnPropertyDelegateQFont, QtnPropertyQFontBase>
                                , "LineEditBttn");

static QtnEnumInfo* styleStrategyEnum()
{
    static QtnEnumInfo* enumInfo = nullptr;
    if (!enumInfo)
    {
        QVector<QtnEnumValueInfo> items;
		items.append(QtnEnumValueInfo(QFont::PreferDefault, QtnPropertyQFont::getPreferDefaultStr()));
		items.append(QtnEnumValueInfo(QFont::NoAntialias, QtnPropertyQFont::getNoAntialiasStr()));
		items.append(QtnEnumValueInfo(QFont::PreferAntialias, QtnPropertyQFont::getPreferAntialiasStr()));
		enumInfo = new QtnEnumInfo("FontStyleStrategy", items);
    }

    return enumInfo;
}

enum
{
	SizeUnitPixel,
	SizeUnitPoint
};

static QtnEnumInfo* sizeUnitEnum()
{
	static QtnEnumInfo* enumInfo = nullptr;
	if (!enumInfo)
	{
		QVector<QtnEnumValueInfo> items;
		items.append(QtnEnumValueInfo(SizeUnitPixel, QtnPropertyQFont::getPixelStr()));
		items.append(QtnEnumValueInfo(SizeUnitPoint, QtnPropertyQFont::getPointStr()));
		enumInfo = new QtnEnumInfo("FontSizeUnit", items);
	}

	return enumInfo;
}

QtnPropertyDelegateQFont::QtnPropertyDelegateQFont(QtnPropertyQFontBase& owner)
    : QtnPropertyDelegateTypedEx<QtnPropertyQFontBase>(owner)
{
    QtnPropertyQStringCallback* propertyFamily = new QtnPropertyQStringCallback(0);
    addSubProperty(propertyFamily);
	propertyFamily->setName(QtnPropertyQFont::getFamilyLabel());
	propertyFamily->setDescription(QtnPropertyQFont::getFamilyDescription(owner.name()));
    propertyFamily->setCallbackValueGet([&owner]()->QString {
        return owner.value().family();
    });
    propertyFamily->setCallbackValueSet([&owner](QString value) {
        QFont font = owner.value();
        font.setFamily(value);
        owner.setValue(font);
    });
    QtnPropertyDelegateInfo delegate;
    delegate.name = "List";
    QFontDatabase fDB;
    delegate.attributes["items"] = fDB.families();
    propertyFamily->setDelegate(delegate);

	QtnPropertyUIntCallback* propertySize = new QtnPropertyUIntCallback(0);
	addSubProperty(propertySize);
	propertySize->setName(QtnPropertyQFont::getSizeLabel());
	propertySize->setDescription(QtnPropertyQFont::getSizeDescription(owner.name()));
	propertySize->setCallbackValueGet([&owner]() -> quint32
	{
        int ps = owner.value().pointSize();
		if (ps < 0)
			ps = owner.value().pixelSize();
		if (ps < 1)
			ps = 1;
		return ps;
    });
	propertySize->setCallbackValueSet([&owner](quint32 value)
	{
		if (value == 0)
			value = 1;

        QFont font = owner.value();
		if (font.pointSize() > 0)
		{
			if (value > 128)
				value = 128;

			font.setPointSize((int) value);
		} else
		{
			if (value > 256)
				value = 256;

			font.setPixelSize((int) value);
		}
        owner.setValue(font);
    });

	QtnPropertyEnumCallback* propertySizeUnit = new QtnPropertyEnumCallback(0);
	addSubProperty(propertySizeUnit);
	propertySizeUnit->setName(QtnPropertyQFont::getSizeUnitLabel());
	propertySizeUnit->setDescription(QtnPropertyQFont::getSizeUnitDescription(owner.name()));
	propertySizeUnit->setEnumInfo(sizeUnitEnum());
	propertySizeUnit->setCallbackValueGet([&owner]() -> QtnEnumValueType
	{
		if (owner.value().pointSize() < 0)
			return SizeUnitPixel;

		return SizeUnitPoint;
	});
	propertySizeUnit->setCallbackValueSet([&owner](QtnEnumValueType value)
	{
		QFont font = owner.value();

		int size = std::max(font.pointSize(), font.pixelSize());

		switch (value)
		{
			case SizeUnitPixel:
				font.setPixelSize(size);
				break;

			case SizeUnitPoint:
				font.setPointSize(size);
				break;

			default:
				break;
		}

		owner.setValue(font);
	});

    QtnPropertyBoolCallback* propertyBold = new QtnPropertyBoolCallback(0);
    addSubProperty(propertyBold);
	propertyBold->setName(QtnPropertyQFont::getBoldLabel());
	propertyBold->setDescription(QtnPropertyQFont::getBoldDescription(owner.name()));
    propertyBold->setCallbackValueGet([&owner]()->bool {
        return owner.value().bold();
    });
    propertyBold->setCallbackValueSet([&owner](bool value) {
        QFont font = owner.value();
        font.setBold(value);
        owner.setValue(font);
    });

    QtnPropertyBoolCallback* propertyItalic = new QtnPropertyBoolCallback(0);
    addSubProperty(propertyItalic);
	propertyItalic->setName(QtnPropertyQFont::getItalicLabel());
	propertyItalic->setDescription(QtnPropertyQFont::getItalicDescription(owner.name()));
    propertyItalic->setCallbackValueGet([&owner]()->bool {
        return owner.value().italic();
    });
    propertyItalic->setCallbackValueSet([&owner](bool value) {
        QFont font = owner.value();
        font.setItalic(value);
        owner.setValue(font);
    });

    QtnPropertyBoolCallback* propertyUnderline = new QtnPropertyBoolCallback(0);
    addSubProperty(propertyUnderline);
	propertyUnderline->setName(QtnPropertyQFont::getUnderlineLabel());
	propertyUnderline->setDescription(QtnPropertyQFont::getUnderlineDescription(owner.name()));
    propertyUnderline->setCallbackValueGet([&owner]()->bool {
        return owner.value().underline();
    });
    propertyUnderline->setCallbackValueSet([&owner](bool value) {
        QFont font = owner.value();
        font.setUnderline(value);
        owner.setValue(font);
    });

    QtnPropertyBoolCallback* propertyStrikeout = new QtnPropertyBoolCallback(0);
    addSubProperty(propertyStrikeout);
	propertyStrikeout->setName(QtnPropertyQFont::getStrikeoutLabel());
	propertyStrikeout->setDescription(QtnPropertyQFont::getStrikeoutDescription(owner.name()));
    propertyStrikeout->setCallbackValueGet([&owner]()->bool {
        return owner.value().strikeOut();
    });
    propertyStrikeout->setCallbackValueSet([&owner](bool value) {
        QFont font = owner.value();
        font.setStrikeOut(value);
        owner.setValue(font);
    });

    QtnPropertyBoolCallback* propertyKerning = new QtnPropertyBoolCallback(0);
    addSubProperty(propertyKerning);
	propertyKerning->setName(QtnPropertyQFont::getKerningLabel());
	propertyKerning->setDescription(QtnPropertyQFont::getKerningDescription(owner.name()));
    propertyKerning->setCallbackValueGet([&owner]()->bool {
        return owner.value().kerning();
    });
    propertyKerning->setCallbackValueSet([&owner](bool value) {
        QFont font = owner.value();
        font.setKerning(value);
        owner.setValue(font);
    });

    QtnPropertyEnumCallback* propertyAntialiasing = new QtnPropertyEnumCallback(0);
    addSubProperty(propertyAntialiasing);
	propertyAntialiasing->setName(QtnPropertyQFont::getAntialiasingLabel());
	propertyAntialiasing->setDescription(QtnPropertyQFont::getAntialiasingDescription(owner.name()));
    propertyAntialiasing->setEnumInfo(styleStrategyEnum());
    propertyAntialiasing->setCallbackValueGet([&owner]()->QtnEnumValueType {
        return owner.value().styleStrategy();
    });
    propertyAntialiasing->setCallbackValueSet([&owner](QtnEnumValueType value) {
        QFont font = owner.value();
        font.setStyleStrategy((QFont::StyleStrategy)value);
        owner.setValue(font);
    });
}

void QtnPropertyDelegateQFont::drawValueImpl(QStylePainter& painter, const QRect& rect, const QStyle::State& state, bool* needTooltip) const
{
    QFont value = owner().value();

    QRect textRect = rect;

    if (textRect.isValid())
    {
        QRect br;

        QFont oldFont = painter.font();
        QFont newFont(value);
        newFont.setPointSize(oldFont.pointSize());
        painter.setFont(newFont);
        painter.drawText(textRect, Qt::AlignLeading | Qt::AlignVCenter, "A", &br);
        painter.setFont(oldFont);

        textRect.setLeft(br.right() + 3);
    }

    if (textRect.isValid())
    {
        QtnPropertyDelegateTypedEx<QtnPropertyQFontBase>::drawValueImpl(painter, textRect, state, needTooltip);
    }
}

QWidget* QtnPropertyDelegateQFont::createValueEditorImpl(QWidget* parent, const QRect& rect, QtnInplaceInfo* inplaceInfo)
{
    QtnLineEditBttn* editor = new QtnLineEditBttn(parent);
    editor->setGeometry(rect);

    new QtnPropertyQFontLineEditBttnHandler(owner(), *editor);

    if (inplaceInfo)
    {
        editor->lineEdit->selectAll();
    }

    return editor;
}

bool QtnPropertyDelegateQFont::propertyValueToStr(QString& strValue) const
{
	strValue = FontToStr(owner().value());
    return true;
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2014-2016 AscEmu Team <http://www.ascemu.org/>
This file is released under the MIT license. See README-MIT for more information.
*/

#include "AreaStorage.hpp"
#include "StdAfx.h"

namespace MapManagement
{
    namespace AreaManagement
    {
        DBC::DBCStorage<DBC::Structures::AreaTableEntry>* AreaStorage::m_storage;
        MapEntryPair AreaStorage::m_map_storage;
        AreaFlagByAreaID AreaStorage::m_area_flag_by_id_collection;
        AreaFlagByMapID AreaStorage::m_area_flag_by_map_id_collection;

        MapEntryPair* AreaStorage::GetMapCollection()
        {
            return &AreaStorage::m_map_storage;
        }

        void AreaStorage::Initialise(DBC::DBCStorage<DBC::Structures::AreaTableEntry>* dbc_storage)
        {
            m_storage = dbc_storage;

            // Preload this stuff to make lookups easier elsewhere in code
            for (uint32 i = 0; i < m_storage->GetNumRows(); ++i)
            {
                if (auto area = m_storage->LookupEntry(i))
                {
                    m_area_flag_by_id_collection.insert(std::map<uint16, uint32>::value_type(uint16(area->id), area->explore_flag));
                    if (area->zone == 0 && area->map_id != 0 && area->map_id != 1 && area->map_id != 530 && area->map_id != 571)
                    {
                        m_area_flag_by_map_id_collection.insert(std::map<uint32, uint32>::value_type(area->map_id, area->explore_flag));
                    }
                }
            }

        }

        DBC::DBCStorage<DBC::Structures::AreaTableEntry>* AreaStorage::GetStorage()
        {
            return m_storage;
        }

        int32 AreaStorage::GetFlagById(uint32 area_id)
        {
            auto iter = m_area_flag_by_id_collection.find(area_id);
            if (iter == m_area_flag_by_id_collection.end())
                return -1;

            return iter->second;
        }

        uint32 AreaStorage::GetFlagByMapId(uint32 map_id)
        {
            auto iter = m_area_flag_by_map_id_collection.find(map_id);
            if (iter == m_area_flag_by_map_id_collection.end())
                return 0;
            else
                return iter->second;
        }

        DBC::Structures::AreaTableEntry const* AreaStorage::GetAreaByFlag(uint32 area_flag)
        {
            return m_storage->LookupEntry(area_flag);
        }

        DBC::Structures::AreaTableEntry const* AreaStorage::GetAreaByMapId(uint32 map_id)
        {
            for (auto map_object : m_map_storage)
            {
                if (map_object.first == map_id)
                {
                    return AreaStorage::GetAreaById(map_object.second);
                }
            }

            return nullptr;
        }

        DBC::Structures::AreaTableEntry const* AreaStorage::GetAreaById(uint32 area_id)
        {
            int32 area_flag = AreaStorage::GetFlagById(area_id);
            if (area_flag < 0)
                return NULL;

            return m_storage->LookupEntry(area_flag);
        }

        void AreaStorage::GetZoneAndIdByFlag(uint32& zone_id, uint32& area_id, uint16 area_flag, uint32 map_id)
        {
            auto area = AreaStorage::GetAreaByFlag(area_flag);
            if (!area)
            {
                area = AreaStorage::GetAreaByMapId(map_id);
            }

            area_id = area ? area->id : 0;
            zone_id = area ? ((area->zone != 0) ? area->zone : area->id) : 0;
        }

        bool AreaStorage::IsOutdoor(uint32 mapId, float x, float y, float z)
        {
            VMAP::IVMapManager* mgr = VMAP::VMapFactory::createOrGetVMapManager();

            uint32 mogpFlags;
            int32 adtId, rootId, groupId;

            if (!mgr->getAreaInfo(mapId, x, y, z, mogpFlags, adtId, rootId, groupId))
                return true;

            DBC::Structures::AreaTableEntry const* atEntry = nullptr;
            DBC::Structures::WMOAreaTableEntry const* wmoEntry = GetWMOAreaTableEntryByTriple(rootId, adtId, groupId);

            if (wmoEntry)
            {
                Log.Map("CCollideInterface::IsOutdoor", "Got WMOAreaTableEntry! flag %u, areaid %u", wmoEntry->flags, wmoEntry->areaId);
                atEntry = sAreaStore.LookupEntry(wmoEntry->areaId);
            }

            return IsOutdoorWMO(mogpFlags, adtId, rootId, groupId, wmoEntry, atEntry);
        }

        bool AreaStorage::IsOutdoorWMO(uint32 mogpFlags, int32 /*adtId*/, int32 /*rootId*/, int32 /*groupId*/, DBC::Structures::WMOAreaTableEntry const* wmoEntry, DBC::Structures::AreaTableEntry const* atEntry)
        {
            bool outdoor = true;

            if (wmoEntry && atEntry)
            {
                if (atEntry->flags & AREA_FLAG_OUTSIDE)
                    return true;
                if (atEntry->flags & AREA_FLAG_INSIDE)
                    return false;
            }

            outdoor = (mogpFlags & 0x8) != 0;

            if (wmoEntry)
            {
                if (wmoEntry->flags & 4)
                    return true;
                if (wmoEntry->flags & 2)
                    outdoor = false;
            }
            return outdoor;
        }

        uint32 AreaStorage::GetIdByFlag(uint32 area_flag)
        {
            auto area = AreaStorage::GetAreaByFlag(area_flag);
            if (area)
                return area->id;
            else
                return 0;
        }

        uint32 AreaStorage::GetIdByMapId(uint32 map_id)
        {
            auto area = AreaStorage::GetAreaByMapId(map_id);
            if (area)
                return area->id;
            else
                return 0;
        }

        const uint16 AreaStorage::GetFlagByPosition(uint16 area_flag_without_adt_id, bool have_area_info, uint32 mogp_flags, int32 adt_id, int32 root_id, int32 group_id, uint32 map_id, float x, float y, float z, bool* _out_is_outdoors)
        {
            ::DBC::Structures::AreaTableEntry const* at_entry = nullptr;
            if (have_area_info)
            {
                auto wmo_triple = GetWMOAreaTableEntryByTriple(root_id, adt_id, group_id);
                if (wmo_triple)
                {
                    at_entry = AreaStorage::GetAreaById(wmo_triple->areaId);
                }
            }

            //uint16 area_flag;

            if (at_entry)
            {
                return at_entry->explore_flag;
            }
            else
            {
                if (area_flag_without_adt_id)
                {
                    return area_flag_without_adt_id;
                }

                return AreaStorage::GetFlagByMapId(map_id);
            }

            /*if (_out_is_outdoors)
            {
                if (have_area_info)
                {
                    *_out_is_outdoors = IsOutdoorWMO(mogp_flags, adt_id, root_id, group_id, wmo_entry, at_entry);
                }
                else
                {
                    *_out_is_outdoors = true;
                }
            }*/

            // Unused
            //return area_flag;
        }
    } // </ AreaManagementNamespace>
} // </ MapManagementNamespace>
<commit_msg>Corrected log message<commit_after>/*
Copyright (c) 2014-2016 AscEmu Team <http://www.ascemu.org/>
This file is released under the MIT license. See README-MIT for more information.
*/

#include "AreaStorage.hpp"
#include "StdAfx.h"

namespace MapManagement
{
    namespace AreaManagement
    {
        DBC::DBCStorage<DBC::Structures::AreaTableEntry>* AreaStorage::m_storage;
        MapEntryPair AreaStorage::m_map_storage;
        AreaFlagByAreaID AreaStorage::m_area_flag_by_id_collection;
        AreaFlagByMapID AreaStorage::m_area_flag_by_map_id_collection;

        MapEntryPair* AreaStorage::GetMapCollection()
        {
            return &AreaStorage::m_map_storage;
        }

        void AreaStorage::Initialise(DBC::DBCStorage<DBC::Structures::AreaTableEntry>* dbc_storage)
        {
            m_storage = dbc_storage;

            // Preload this stuff to make lookups easier elsewhere in code
            for (uint32 i = 0; i < m_storage->GetNumRows(); ++i)
            {
                if (auto area = m_storage->LookupEntry(i))
                {
                    m_area_flag_by_id_collection.insert(std::map<uint16, uint32>::value_type(uint16(area->id), area->explore_flag));
                    if (area->zone == 0 && area->map_id != 0 && area->map_id != 1 && area->map_id != 530 && area->map_id != 571)
                    {
                        m_area_flag_by_map_id_collection.insert(std::map<uint32, uint32>::value_type(area->map_id, area->explore_flag));
                    }
                }
            }

        }

        DBC::DBCStorage<DBC::Structures::AreaTableEntry>* AreaStorage::GetStorage()
        {
            return m_storage;
        }

        int32 AreaStorage::GetFlagById(uint32 area_id)
        {
            auto iter = m_area_flag_by_id_collection.find(area_id);
            if (iter == m_area_flag_by_id_collection.end())
                return -1;

            return iter->second;
        }

        uint32 AreaStorage::GetFlagByMapId(uint32 map_id)
        {
            auto iter = m_area_flag_by_map_id_collection.find(map_id);
            if (iter == m_area_flag_by_map_id_collection.end())
                return 0;
            else
                return iter->second;
        }

        DBC::Structures::AreaTableEntry const* AreaStorage::GetAreaByFlag(uint32 area_flag)
        {
            return m_storage->LookupEntry(area_flag);
        }

        DBC::Structures::AreaTableEntry const* AreaStorage::GetAreaByMapId(uint32 map_id)
        {
            for (auto map_object : m_map_storage)
            {
                if (map_object.first == map_id)
                {
                    return AreaStorage::GetAreaById(map_object.second);
                }
            }

            return nullptr;
        }

        DBC::Structures::AreaTableEntry const* AreaStorage::GetAreaById(uint32 area_id)
        {
            int32 area_flag = AreaStorage::GetFlagById(area_id);
            if (area_flag < 0)
                return NULL;

            return m_storage->LookupEntry(area_flag);
        }

        void AreaStorage::GetZoneAndIdByFlag(uint32& zone_id, uint32& area_id, uint16 area_flag, uint32 map_id)
        {
            auto area = AreaStorage::GetAreaByFlag(area_flag);
            if (!area)
            {
                area = AreaStorage::GetAreaByMapId(map_id);
            }

            area_id = area ? area->id : 0;
            zone_id = area ? ((area->zone != 0) ? area->zone : area->id) : 0;
        }

        bool AreaStorage::IsOutdoor(uint32 mapId, float x, float y, float z)
        {
            VMAP::IVMapManager* mgr = VMAP::VMapFactory::createOrGetVMapManager();

            uint32 mogpFlags;
            int32 adtId, rootId, groupId;

            if (!mgr->getAreaInfo(mapId, x, y, z, mogpFlags, adtId, rootId, groupId))
                return true;

            DBC::Structures::AreaTableEntry const* atEntry = nullptr;
            DBC::Structures::WMOAreaTableEntry const* wmoEntry = GetWMOAreaTableEntryByTriple(rootId, adtId, groupId);

            if (wmoEntry)
            {
                Log.Map("AreaStorage::IsOutdoor", "Got WMOAreaTableEntry! flag %u, areaid %u", wmoEntry->flags, wmoEntry->areaId);
                atEntry = sAreaStore.LookupEntry(wmoEntry->areaId);
            }

            return IsOutdoorWMO(mogpFlags, adtId, rootId, groupId, wmoEntry, atEntry);
        }

        bool AreaStorage::IsOutdoorWMO(uint32 mogpFlags, int32 /*adtId*/, int32 /*rootId*/, int32 /*groupId*/, DBC::Structures::WMOAreaTableEntry const* wmoEntry, DBC::Structures::AreaTableEntry const* atEntry)
        {
            bool outdoor = true;

            if (wmoEntry && atEntry)
            {
                if (atEntry->flags & AREA_FLAG_OUTSIDE)
                    return true;
                if (atEntry->flags & AREA_FLAG_INSIDE)
                    return false;
            }

            outdoor = (mogpFlags & 0x8) != 0;

            if (wmoEntry)
            {
                if (wmoEntry->flags & 4)
                    return true;
                if (wmoEntry->flags & 2)
                    outdoor = false;
            }
            return outdoor;
        }

        uint32 AreaStorage::GetIdByFlag(uint32 area_flag)
        {
            auto area = AreaStorage::GetAreaByFlag(area_flag);
            if (area)
                return area->id;
            else
                return 0;
        }

        uint32 AreaStorage::GetIdByMapId(uint32 map_id)
        {
            auto area = AreaStorage::GetAreaByMapId(map_id);
            if (area)
                return area->id;
            else
                return 0;
        }

        const uint16 AreaStorage::GetFlagByPosition(uint16 area_flag_without_adt_id, bool have_area_info, uint32 mogp_flags, int32 adt_id, int32 root_id, int32 group_id, uint32 map_id, float x, float y, float z, bool* _out_is_outdoors)
        {
            ::DBC::Structures::AreaTableEntry const* at_entry = nullptr;
            if (have_area_info)
            {
                auto wmo_triple = GetWMOAreaTableEntryByTriple(root_id, adt_id, group_id);
                if (wmo_triple)
                {
                    at_entry = AreaStorage::GetAreaById(wmo_triple->areaId);
                }
            }

            //uint16 area_flag;

            if (at_entry)
            {
                return at_entry->explore_flag;
            }
            else
            {
                if (area_flag_without_adt_id)
                {
                    return area_flag_without_adt_id;
                }

                return AreaStorage::GetFlagByMapId(map_id);
            }

            /*if (_out_is_outdoors)
            {
                if (have_area_info)
                {
                    *_out_is_outdoors = IsOutdoorWMO(mogp_flags, adt_id, root_id, group_id, wmo_entry, at_entry);
                }
                else
                {
                    *_out_is_outdoors = true;
                }
            }*/

            // Unused
            //return area_flag;
        }
    } // </ AreaManagementNamespace>
} // </ MapManagementNamespace>
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2002-2003 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#if !defined(XERCESVERSION_HPP)
#define XERCESVERSION_HPP

// ---------------------------------------------------------------------------
// X E R C E S   V E R S I O N   H E A D E R   D O C U M E N T A T I O N

/**
 * User Documentation for Xerces Version Values:
 *
 *
 *
 * Xerces  Notes:
 *
 * Xerces Committers Documentation:
 *
 *    Xerces committers normally only need to modify one or two of the
 *    following macros:
 *
 *      XERCES_VERSION_MAJOR
 *      XERCES_VERSION_MINOR
 *      XERCES_VERSION_REVISION
 *
 *    The integer values of these macros define the Xerces version number. All
 *    other constants and preprocessor macros are automatically generated from
 *    these three definitions.
 *
 *    The macro XERCES_GRAMMAR_SERIALIZATION_LEVEL has been added so that during
 *    development if users are using the latest code they can use the grammar
 *    serialization/desialization features.  Whenever a change is made to the
 *    serialization code this macro should be incremented.
 *
 * Xerces User Documentation:
 *
 *  The following sections in the user documentation have examples based upon
 *  the following three version input values:
 *
 *    #define XERCES_VERSION_MAJOR 19
 *    #define XERCES_VERSION_MINOR 3
 *    #define XERCES_VERSION_REVISION 74
 *
 *  The minor and revision (patch level) numbers have two digits of resolution
 *  which means that '3' becomes '03' in this example. This policy guarantees
 *  that when using preprocessor macros, version 19.3.74 will be greater than
 *  version 1.94.74 since the first will expand to 190374 and the second to
 *  19474.
 *
 *  Preprocessor Macros:
 *
 *    _XERCES_VERSION defines the primary preprocessor macro that users will
 *    introduce into their code to perform conditional compilation where the
 *    version of Xerces is detected in order to enable or disable version
 *    specific capabilities. The value of _XERCES_VERSION for the above example
 *    will be 190374. To use it a user would perform an operation such as the
 *    following:
 *
 *      #if _XERCES_VERSION >= 190374
 *        // code specific to new version of Xerces...
 *      #else
 *        // old code here...
 *      #endif
 *
 *    XERCES_FULLVERSIONSTR is a preprocessor macro that expands to a string
 *    constant whose value, for the above example, will be "19_3_74".
 *
 *    XERCES_FULLVERSIONDOT is a preprocessor macro that expands to a string
 *    constant whose value, for the above example, will be "19.3.74".
 *
 *    XERCES_VERSIONSTR is a preprocessor macro that expands to a string
 *    constant whose value, for the above example, will be "19_3". This
 *    particular macro is very dangerous if it were to be used for comparing
 *    version numbers since ordering will not be guaranteed.
 *
 *    Xerces_DLLVersionStr is a preprocessor macro that expands to a string
 *    constant whose value, for the above example, will be "19_3_74". This
 *    macro is provided for backwards compatibility to pre-1.7 versions of
 *    Xerces.
 *
 *  String Constants:
 *
 *    gXercesVersionStr is a global string constant whose value corresponds to
 *    the value "19_3" for the above example.
 *
 *    gXercesFullVersionStr is a global string constant whose value corresponds
 *    to the value "19_3_74" for the above example.
 *
 *  Numeric Constants:
 *
 *    gXercesMajVersion is a global integer constant whose value corresponds to
 *    the major version number. For the above example its value will be 19.
 *
 *    gXercesMinVersion is a global integer constant whose value corresponds to
 *    the minor version number. For the above example its value will be 3.
 *
 *    gXercesRevision is a global integer constant whose value corresponds to
 *    the revision (patch) version number. For the above example its value will
 *    be 74.
 *
 */

// ---------------------------------------------------------------------------
// X E R C E S   V E R S I O N   S P E C I F I C A T I O N

/**
 * MODIFY THESE NUMERIC VALUES TO COINCIDE WITH XERCES VERSION
 * AND DO NOT MODIFY ANYTHING ELSE IN THIS VERSION HEADER FILE
 */

#define XERCES_VERSION_MAJOR 2
#define XERCES_VERSION_MINOR 5
#define XERCES_VERSION_REVISION 0

#define XERCES_GRAMMAR_SERIALIZATION_LEVEL 2

/** DO NOT MODIFY BELOW THIS LINE */

/**
 * MAGIC THAT AUTOMATICALLY GENERATES THE FOLLOWING:
 *
 *	Xerces_DLLVersionStr, gXercesVersionStr, gXercesFullVersionStr,
 *	gXercesMajVersion, gXercesMinVersion, gXercesRevision
 */

// ---------------------------------------------------------------------------
// T W O   A R G U M E N T   C O N C A T E N A T I O N   M A C R O S

// two argument concatenation routines
#define CAT2_SEP_UNDERSCORE(a, b) #a "_" #b
#define CAT2_SEP_PERIOD(a, b) #a "." #b
#define CAT2_SEP_NIL(a, b) #a #b
#define CAT2_RAW_NUMERIC(a, b) a ## b

// two argument macro invokers
#define INVK_CAT2_SEP_UNDERSCORE(a,b) CAT2_SEP_UNDERSCORE(a,b)
#define INVK_CAT2_SEP_PERIOD(a,b)     CAT2_SEP_PERIOD(a,b)
#define INVK_CAT2_STR_SEP_NIL(a,b)    CAT2_SEP_NIL(a,b)
#define INVK_CAT2_RAW_NUMERIC(a,b)    CAT2_RAW_NUMERIC(a,b)

// ---------------------------------------------------------------------------
// T H R E E   A R G U M E N T   C O N C A T E N A T I O N   M A C R O S

// three argument concatenation routines
#define CAT3_SEP_UNDERSCORE(a, b, c) #a "_" #b "_" #c
#define CAT3_SEP_PERIOD(a, b, c) #a "." #b "." #c
#define CAT3_SEP_NIL(a, b, c) #a #b #c
#define CAT3_RAW_NUMERIC(a, b, c) a ## b ## c
#define CAT3_RAW_NUMERIC_SEP_UNDERSCORE(a, b, c) a ## _ ## b ## _ ## c

// three argument macro invokers
#define INVK_CAT3_SEP_UNDERSCORE(a,b,c) CAT3_SEP_UNDERSCORE(a,b,c)
#define INVK_CAT3_SEP_PERIOD(a,b,c)     CAT3_SEP_PERIOD(a,b,c)
#define INVK_CAT3_SEP_NIL(a,b,c)        CAT3_SEP_NIL(a,b,c)
#define INVK_CAT3_RAW_NUMERIC(a,b,c)    CAT3_RAW_NUMERIC(a,b,c)
#define INVK_CAT3_RAW_NUMERIC_SEP_UNDERSCORE(a,b,c)    CAT3_RAW_NUMERIC_SEP_UNDERSCORE(a,b,c)

// ---------------------------------------------------------------------------
// C A L C U L A T E   V E R S I O N   -   E X P A N D E D   F O R M

#define MULTIPLY(factor,value) factor * value
#define CALC_EXPANDED_FORM(a,b,c) ( MULTIPLY(10000,a) + MULTIPLY(100,b) + MULTIPLY(1,c) )

// ---------------------------------------------------------------------------
// X E R C E S   V E R S I O N   I N F O R M A T I O N

// Xerces version strings; these particular macros cannot be used for
// conditional compilation as they are not numeric constants

#define XERCES_FULLVERSIONSTR INVK_CAT3_SEP_UNDERSCORE(XERCES_VERSION_MAJOR,XERCES_VERSION_MINOR,XERCES_VERSION_REVISION)
#define XERCES_FULLVERSIONDOT INVK_CAT3_SEP_PERIOD(XERCES_VERSION_MAJOR,XERCES_VERSION_MINOR,XERCES_VERSION_REVISION)
#define XERCES_FULLVERSIONNUM INVK_CAT3_SEP_NIL(XERCES_VERSION_MAJOR,XERCES_VERSION_MINOR,XERCES_VERSION_REVISION)
#define XERCES_VERSIONSTR     INVK_CAT2_SEP_UNDERSCORE(XERCES_VERSION_MAJOR,XERCES_VERSION_MINOR)

// Xerces C++ Namespace string, concatenated with full version string
#define XERCES_PRODUCT xercesc
#define XERCES_CPP_NAMESPACE INVK_CAT3_RAW_NUMERIC_SEP_UNDERSCORE(XERCES_PRODUCT,XERCES_VERSION_MAJOR,XERCES_VERSION_MINOR)

// original from Xerces header
#define Xerces_DLLVersionStr XERCES_FULLVERSIONSTR

const char* const    gXercesVersionStr = XERCES_VERSIONSTR;
const char* const    gXercesFullVersionStr = XERCES_FULLVERSIONSTR;
const unsigned int   gXercesMajVersion = XERCES_VERSION_MAJOR;
const unsigned int   gXercesMinVersion = XERCES_VERSION_MINOR;
const unsigned int   gXercesRevision   = XERCES_VERSION_REVISION;

// Xerces version numeric constants that can be used for conditional
// compilation purposes.

#define _XERCES_VERSION CALC_EXPANDED_FORM (XERCES_VERSION_MAJOR,XERCES_VERSION_MINOR,XERCES_VERSION_REVISION)

#endif // XERCESVERSION_HPP
<commit_msg>version number bump<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2002-2003 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#if !defined(XERCESVERSION_HPP)
#define XERCESVERSION_HPP

// ---------------------------------------------------------------------------
// X E R C E S   V E R S I O N   H E A D E R   D O C U M E N T A T I O N

/**
 * User Documentation for Xerces Version Values:
 *
 *
 *
 * Xerces  Notes:
 *
 * Xerces Committers Documentation:
 *
 *    Xerces committers normally only need to modify one or two of the
 *    following macros:
 *
 *      XERCES_VERSION_MAJOR
 *      XERCES_VERSION_MINOR
 *      XERCES_VERSION_REVISION
 *
 *    The integer values of these macros define the Xerces version number. All
 *    other constants and preprocessor macros are automatically generated from
 *    these three definitions.
 *
 *    The macro XERCES_GRAMMAR_SERIALIZATION_LEVEL has been added so that during
 *    development if users are using the latest code they can use the grammar
 *    serialization/desialization features.  Whenever a change is made to the
 *    serialization code this macro should be incremented.
 *
 * Xerces User Documentation:
 *
 *  The following sections in the user documentation have examples based upon
 *  the following three version input values:
 *
 *    #define XERCES_VERSION_MAJOR 19
 *    #define XERCES_VERSION_MINOR 3
 *    #define XERCES_VERSION_REVISION 74
 *
 *  The minor and revision (patch level) numbers have two digits of resolution
 *  which means that '3' becomes '03' in this example. This policy guarantees
 *  that when using preprocessor macros, version 19.3.74 will be greater than
 *  version 1.94.74 since the first will expand to 190374 and the second to
 *  19474.
 *
 *  Preprocessor Macros:
 *
 *    _XERCES_VERSION defines the primary preprocessor macro that users will
 *    introduce into their code to perform conditional compilation where the
 *    version of Xerces is detected in order to enable or disable version
 *    specific capabilities. The value of _XERCES_VERSION for the above example
 *    will be 190374. To use it a user would perform an operation such as the
 *    following:
 *
 *      #if _XERCES_VERSION >= 190374
 *        // code specific to new version of Xerces...
 *      #else
 *        // old code here...
 *      #endif
 *
 *    XERCES_FULLVERSIONSTR is a preprocessor macro that expands to a string
 *    constant whose value, for the above example, will be "19_3_74".
 *
 *    XERCES_FULLVERSIONDOT is a preprocessor macro that expands to a string
 *    constant whose value, for the above example, will be "19.3.74".
 *
 *    XERCES_VERSIONSTR is a preprocessor macro that expands to a string
 *    constant whose value, for the above example, will be "19_3". This
 *    particular macro is very dangerous if it were to be used for comparing
 *    version numbers since ordering will not be guaranteed.
 *
 *    Xerces_DLLVersionStr is a preprocessor macro that expands to a string
 *    constant whose value, for the above example, will be "19_3_74". This
 *    macro is provided for backwards compatibility to pre-1.7 versions of
 *    Xerces.
 *
 *  String Constants:
 *
 *    gXercesVersionStr is a global string constant whose value corresponds to
 *    the value "19_3" for the above example.
 *
 *    gXercesFullVersionStr is a global string constant whose value corresponds
 *    to the value "19_3_74" for the above example.
 *
 *  Numeric Constants:
 *
 *    gXercesMajVersion is a global integer constant whose value corresponds to
 *    the major version number. For the above example its value will be 19.
 *
 *    gXercesMinVersion is a global integer constant whose value corresponds to
 *    the minor version number. For the above example its value will be 3.
 *
 *    gXercesRevision is a global integer constant whose value corresponds to
 *    the revision (patch) version number. For the above example its value will
 *    be 74.
 *
 */

// ---------------------------------------------------------------------------
// X E R C E S   V E R S I O N   S P E C I F I C A T I O N

/**
 * MODIFY THESE NUMERIC VALUES TO COINCIDE WITH XERCES VERSION
 * AND DO NOT MODIFY ANYTHING ELSE IN THIS VERSION HEADER FILE
 */

#define XERCES_VERSION_MAJOR 2
#define XERCES_VERSION_MINOR 5
#define XERCES_VERSION_REVISION 0

/***
 * data member added to XSAnnotation
 ***/
#define XERCES_GRAMMAR_SERIALIZATION_LEVEL 3

/** DO NOT MODIFY BELOW THIS LINE */

/**
 * MAGIC THAT AUTOMATICALLY GENERATES THE FOLLOWING:
 *
 *	Xerces_DLLVersionStr, gXercesVersionStr, gXercesFullVersionStr,
 *	gXercesMajVersion, gXercesMinVersion, gXercesRevision
 */

// ---------------------------------------------------------------------------
// T W O   A R G U M E N T   C O N C A T E N A T I O N   M A C R O S

// two argument concatenation routines
#define CAT2_SEP_UNDERSCORE(a, b) #a "_" #b
#define CAT2_SEP_PERIOD(a, b) #a "." #b
#define CAT2_SEP_NIL(a, b) #a #b
#define CAT2_RAW_NUMERIC(a, b) a ## b

// two argument macro invokers
#define INVK_CAT2_SEP_UNDERSCORE(a,b) CAT2_SEP_UNDERSCORE(a,b)
#define INVK_CAT2_SEP_PERIOD(a,b)     CAT2_SEP_PERIOD(a,b)
#define INVK_CAT2_STR_SEP_NIL(a,b)    CAT2_SEP_NIL(a,b)
#define INVK_CAT2_RAW_NUMERIC(a,b)    CAT2_RAW_NUMERIC(a,b)

// ---------------------------------------------------------------------------
// T H R E E   A R G U M E N T   C O N C A T E N A T I O N   M A C R O S

// three argument concatenation routines
#define CAT3_SEP_UNDERSCORE(a, b, c) #a "_" #b "_" #c
#define CAT3_SEP_PERIOD(a, b, c) #a "." #b "." #c
#define CAT3_SEP_NIL(a, b, c) #a #b #c
#define CAT3_RAW_NUMERIC(a, b, c) a ## b ## c
#define CAT3_RAW_NUMERIC_SEP_UNDERSCORE(a, b, c) a ## _ ## b ## _ ## c

// three argument macro invokers
#define INVK_CAT3_SEP_UNDERSCORE(a,b,c) CAT3_SEP_UNDERSCORE(a,b,c)
#define INVK_CAT3_SEP_PERIOD(a,b,c)     CAT3_SEP_PERIOD(a,b,c)
#define INVK_CAT3_SEP_NIL(a,b,c)        CAT3_SEP_NIL(a,b,c)
#define INVK_CAT3_RAW_NUMERIC(a,b,c)    CAT3_RAW_NUMERIC(a,b,c)
#define INVK_CAT3_RAW_NUMERIC_SEP_UNDERSCORE(a,b,c)    CAT3_RAW_NUMERIC_SEP_UNDERSCORE(a,b,c)

// ---------------------------------------------------------------------------
// C A L C U L A T E   V E R S I O N   -   E X P A N D E D   F O R M

#define MULTIPLY(factor,value) factor * value
#define CALC_EXPANDED_FORM(a,b,c) ( MULTIPLY(10000,a) + MULTIPLY(100,b) + MULTIPLY(1,c) )

// ---------------------------------------------------------------------------
// X E R C E S   V E R S I O N   I N F O R M A T I O N

// Xerces version strings; these particular macros cannot be used for
// conditional compilation as they are not numeric constants

#define XERCES_FULLVERSIONSTR INVK_CAT3_SEP_UNDERSCORE(XERCES_VERSION_MAJOR,XERCES_VERSION_MINOR,XERCES_VERSION_REVISION)
#define XERCES_FULLVERSIONDOT INVK_CAT3_SEP_PERIOD(XERCES_VERSION_MAJOR,XERCES_VERSION_MINOR,XERCES_VERSION_REVISION)
#define XERCES_FULLVERSIONNUM INVK_CAT3_SEP_NIL(XERCES_VERSION_MAJOR,XERCES_VERSION_MINOR,XERCES_VERSION_REVISION)
#define XERCES_VERSIONSTR     INVK_CAT2_SEP_UNDERSCORE(XERCES_VERSION_MAJOR,XERCES_VERSION_MINOR)

// Xerces C++ Namespace string, concatenated with full version string
#define XERCES_PRODUCT xercesc
#define XERCES_CPP_NAMESPACE INVK_CAT3_RAW_NUMERIC_SEP_UNDERSCORE(XERCES_PRODUCT,XERCES_VERSION_MAJOR,XERCES_VERSION_MINOR)

// original from Xerces header
#define Xerces_DLLVersionStr XERCES_FULLVERSIONSTR

const char* const    gXercesVersionStr = XERCES_VERSIONSTR;
const char* const    gXercesFullVersionStr = XERCES_FULLVERSIONSTR;
const unsigned int   gXercesMajVersion = XERCES_VERSION_MAJOR;
const unsigned int   gXercesMinVersion = XERCES_VERSION_MINOR;
const unsigned int   gXercesRevision   = XERCES_VERSION_REVISION;

// Xerces version numeric constants that can be used for conditional
// compilation purposes.

#define _XERCES_VERSION CALC_EXPANDED_FORM (XERCES_VERSION_MAJOR,XERCES_VERSION_MINOR,XERCES_VERSION_REVISION)

#endif // XERCESVERSION_HPP
<|endoftext|>


<commit_before>//  Copyright 2010 Gregory Szorc
//
//  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 "zippylog/platform.hpp"

#include <gtest/gtest.h>

using namespace ::zippylog::platform;

TEST(TimerTest, CreateTimers)
{
    ASSERT_NO_THROW(Timer t(1000000));

    Timer t(100000);
    ASSERT_NO_THROW(t.Start());
    ASSERT_FALSE(t.Signaled());
    sleep(105);
    ASSERT_TRUE(t.Signaled());

    ASSERT_TRUE(t.Reset());
    ASSERT_FALSE(t.Signaled());

    ASSERT_TRUE(t.Start(50000));
    ASSERT_FALSE(t.Signaled());
    sleep(51);
    ASSERT_TRUE(t.Signaled());

    ASSERT_TRUE(t.Start(100000));
    ASSERT_TRUE(t.Reset());
    ASSERT_FALSE(t.Signaled());
    sleep(105);
    ASSERT_FALSE(t.Signaled());
}

<commit_msg>add some time tests; change asserts to expects<commit_after>//  Copyright 2010 Gregory Szorc
//
//  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 "zippylog/platform.hpp"

#include <gtest/gtest.h>

using namespace ::zippylog::platform;

TEST(TimerTest, CreateTimers)
{
    ASSERT_NO_THROW(Timer t(1000000));

    Timer t(100000);
    ASSERT_NO_THROW(t.Start());
    EXPECT_FALSE(t.Signaled());
    sleep(105);
    EXPECT_TRUE(t.Signaled());

    EXPECT_TRUE(t.Reset());
    EXPECT_FALSE(t.Signaled());

    EXPECT_TRUE(t.Start(50000));
    EXPECT_FALSE(t.Signaled());
    sleep(51);
    EXPECT_TRUE(t.Signaled());

    EXPECT_TRUE(t.Start(100000));
    EXPECT_TRUE(t.Reset());
    EXPECT_FALSE(t.Signaled());
    sleep(105);
    EXPECT_FALSE(t.Signaled());
}

TEST(TimeTest, TimeConversion)
{
    Time t;
    ASSERT_TRUE(UnixMicroTimeToZippyTime(0, t));
    EXPECT_EQ(1970, t.year);
    EXPECT_EQ(1, t.mon);
    EXPECT_EQ(1, t.mday);
    EXPECT_EQ(0, t.epoch_sec);
    EXPECT_EQ(0, t.epoch_micro);
    EXPECT_EQ(0, t.usec);
    EXPECT_EQ(0, t.hour);
    EXPECT_EQ(0, t.min);
    EXPECT_EQ(0, t.sec);
    EXPECT_EQ(0, t.yday);
    EXPECT_EQ(4, t.wday);

    ASSERT_TRUE(UnixMicroTimeToZippyTime(1234567890000000, t));
    EXPECT_EQ(2009, t.year);
    EXPECT_EQ(2, t.mon);
    EXPECT_EQ(13, t.mday);
    EXPECT_EQ(1234567890, t.epoch_sec);
    EXPECT_EQ(1234567890000000, t.epoch_micro);
    EXPECT_EQ(0, t.usec);
    EXPECT_EQ(23, t.hour);
    EXPECT_EQ(31, t.min);
    EXPECT_EQ(30, t.sec);
    EXPECT_EQ(43, t.yday);
    EXPECT_EQ(5, t.wday);

    ASSERT_TRUE(UnixMicroTimeToZippyTime(1234567890001024, t));
    EXPECT_EQ(2009, t.year);
    EXPECT_EQ(2, t.mon);
    EXPECT_EQ(13, t.mday);
    EXPECT_EQ(1234567890, t.epoch_sec);
    EXPECT_EQ(1234567890001024, t.epoch_micro);
    EXPECT_EQ(1024, t.usec);
    EXPECT_EQ(23, t.hour);
    EXPECT_EQ(31, t.min);
    EXPECT_EQ(30, t.sec);
    EXPECT_EQ(43, t.yday);
    EXPECT_EQ(5, t.wday);
}
<|endoftext|>


<commit_before>#ifndef SYSTEM_CONTROLS_HPP
#define SYSTEM_CONTROLS_HPP

#include "components/position.hpp"
#include "components/player.hpp"
#include "components/velocity.hpp"
#include "components/collidable.hpp"
#include "components/drawable.hpp"
#include "events.hpp"
#include "animation.hpp"

#include "game_config.hpp"
#include "game.hpp"

#include <glm/vec2.hpp>
#include <glm/glm.hpp>
#include <glm/common.hpp>

#ifdef __EMSCRIPTEN__
#include <SDL/SDL_mixer.h>
#else
#include <SDL_mixer.h>
#endif

#include<iostream>

class ControlSystem : public entityx::System<ControlSystem>, public entityx::Receiver<ControlSystem> {
    public:
        ControlSystem(Game *game): game(game), stoppedSpace(false), died(false), freezecount(0), mutecount(0) {}

        void configure(entityx::EventManager &event_manager) override {
            event_manager.subscribe<GameOver>(*this);
        }

        void receive(const GameOver &event) {
            (void)event;
            died = true;
        }

        void update(entityx::EntityManager &es, entityx::EventManager &events, double dt) {
            entityx::ComponentHandle<Player> player;
            entityx::ComponentHandle<Velocity> velocity;
            entityx::ComponentHandle<Position> position;
            entityx::ComponentHandle<Collidable> collidable;
            entityx::ComponentHandle<Drawable> drawable;

            const Uint8 *state = SDL_GetKeyboardState(NULL);
            std::cout << this->game->getSanity() << std::endl;
            if (state[SDL_SCANCODE_R]) {
              std::cout << "reset" << std::endl;
              rand();
              this->game->reset();
            }
            if (state[SDL_SCANCODE_T]) {
              std::cout << "reset" << std::endl;
              this->game->reset();
            }

            freezecount += dt;
            mutecount += dt;
            for (entityx::Entity entity : es.entities_with_components(player, velocity, position, collidable, drawable)) {
                (void) entity;

                bool walking = false;
                if (state[SDL_SCANCODE_RETURN]) {
                    if (freezecount > 0.5) {
                      this->game->toggleFreeze();
                      freezecount = 0;
                    }
                }
                if ((state[SDL_SCANCODE_A] || state[SDL_SCANCODE_LEFT]) && !player->isJumping()) {
                    velocity->drag(glm::vec2(-.3f, 0.0f) * SPEED);
                    walking = true;
                }
                if (state[SDL_SCANCODE_M]) {
                    if (mutecount > 0.2) {
                      this->game->toggleMute();
                      std::cout << "mute" << std::endl;
                      mutecount = 0;
                    }
                }
                if (state[SDL_SCANCODE_D] || state[SDL_SCANCODE_RIGHT] || HARDCORE) {
                    velocity->drag(glm::vec2(1.0f, 0.0f) * SPEED);
                    walking = true;
                }
                if (state[SDL_SCANCODE_SPACE] || state[SDL_SCANCODE_W] || state[SDL_SCANCODE_UP]) {
                    if (!stoppedSpace) {
                        if (!player->isJumping()) {
                            drawable->getAnimation().setAnimation("jump", AnimationPlaybackType::FREEZE);
                        }
                        player->jumping(dt);
                        if (player->getJumpTime() > 0) {
                            velocity->drag(glm::vec2(0, -JUMP_SPEED));
                        }
                    }
                } else {
                    if (player->isJumping()) {
                        stoppedSpace = true;
                    }
                    if (collidable->isTouching()){
                        player->resetJumpTime();
                        stoppedSpace = false;
                        auto& animation = drawable->getAnimation();
                        if(animation.getCurrentAnimation() != "run" && animation.getCurrentAnimation() != "dissolve") {
                            animation.pause(false);
                            animation.setAnimation("run", AnimationPlaybackType::LOOP);
                            Mix_Volume(2, 50);
                            Mix_PlayChannel(2, game->res_manager().sound("landing"), 0);
                        }
                    }
                }
                if (drawable->getAnimation().getCurrentAnimation() != "dissolve") {
                    if (walking && !player->isJumping()) {
                        drawable->getAnimation().pause(false);
                    } else {
                        drawable->getAnimation().pause(true);
                    }
                }
            }
        }
    private:
        Game *game;
        bool stoppedSpace;
        bool died;
        double freezecount;
        double mutecount;
};

#endif
<commit_msg>fix merge<commit_after>#ifndef SYSTEM_CONTROLS_HPP
#define SYSTEM_CONTROLS_HPP

#include "components/position.hpp"
#include "components/player.hpp"
#include "components/velocity.hpp"
#include "components/collidable.hpp"
#include "components/drawable.hpp"
#include "events.hpp"
#include "animation.hpp"

#include "game_config.hpp"
#include "game.hpp"

#include <glm/vec2.hpp>
#include <glm/glm.hpp>
#include <glm/common.hpp>

#ifdef __EMSCRIPTEN__
#include <SDL/SDL_mixer.h>
#else
#include <SDL_mixer.h>
#endif

#include<iostream>

class ControlSystem : public entityx::System<ControlSystem>, public entityx::Receiver<ControlSystem> {
    public:
        ControlSystem(Game *game): game(game), stoppedSpace(false), died(false), freezecount(0), mutecount(0) {}

        void configure(entityx::EventManager &event_manager) override {
            event_manager.subscribe<GameOver>(*this);
        }

        void receive(const GameOver &event) {
            (void)event;
            died = true;
        }

        void update(entityx::EntityManager &es, entityx::EventManager &events, double dt) {
            entityx::ComponentHandle<Player> player;
            entityx::ComponentHandle<Velocity> velocity;
            entityx::ComponentHandle<Position> position;
            entityx::ComponentHandle<Collidable> collidable;
            entityx::ComponentHandle<Drawable> drawable;

            const Uint8 *state = SDL_GetKeyboardState(NULL);
            std::cout << this->game->getSanity() << std::endl;
            if (state[SDL_SCANCODE_R]) {
              std::cout << "reset" << std::endl;
              rand();
              this->game->toggleFreeze();
              this->game->reset();
            }
            if (state[SDL_SCANCODE_T]) {
              std::cout << "reset" << std::endl;
              this->game->toggleFreeze();
              this->game->reset();
            }
            if (died) {
              return;
            }

            freezecount += dt;
            mutecount += dt;
            for (entityx::Entity entity : es.entities_with_components(player, velocity, position, collidable, drawable)) {
                (void) entity;

                bool walking = false;
                if (state[SDL_SCANCODE_RETURN]) {
                    if (freezecount > 0.5) {
                      this->game->toggleFreeze();
                      freezecount = 0;
                    }
                }
                if ((state[SDL_SCANCODE_A] || state[SDL_SCANCODE_LEFT]) && !player->isJumping()) {
                    velocity->drag(glm::vec2(-.3f, 0.0f) * SPEED);
                    walking = true;
                }
                if (state[SDL_SCANCODE_M]) {
                    if (mutecount > 0.2) {
                      this->game->toggleMute();
                      std::cout << "mute" << std::endl;
                      mutecount = 0;
                    }
                }
                if (state[SDL_SCANCODE_D] || state[SDL_SCANCODE_RIGHT] || HARDCORE) {
                    velocity->drag(glm::vec2(1.0f, 0.0f) * SPEED);
                    walking = true;
                }
                if (state[SDL_SCANCODE_SPACE] || state[SDL_SCANCODE_W] || state[SDL_SCANCODE_UP]) {
                    if (!stoppedSpace) {
                        if (!player->isJumping()) {
                            drawable->getAnimation().setAnimation("jump", AnimationPlaybackType::FREEZE);
                        }
                        player->jumping(dt);
                        if (player->getJumpTime() > 0) {
                            velocity->drag(glm::vec2(0, -JUMP_SPEED));
                        }
                    }
                } else {
                    if (player->isJumping()) {
                        stoppedSpace = true;
                    }
                    if (collidable->isTouching()){
                        player->resetJumpTime();
                        stoppedSpace = false;
                        auto& animation = drawable->getAnimation();
                        if(animation.getCurrentAnimation() != "run" && animation.getCurrentAnimation() != "dissolve") {
                            animation.pause(false);
                            animation.setAnimation("run", AnimationPlaybackType::LOOP);
                            Mix_Volume(2, 50);
                            Mix_PlayChannel(2, game->res_manager().sound("landing"), 0);
                        }
                    }
                }
                if (drawable->getAnimation().getCurrentAnimation() != "dissolve") {
                    if (walking && !player->isJumping()) {
                        drawable->getAnimation().pause(false);
                    } else {
                        drawable->getAnimation().pause(true);
                    }
                }
            }
        }
    private:
        Game *game;
        bool stoppedSpace;
        bool died;
        double freezecount;
        double mutecount;
};

#endif
<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org)             */
/*                                                                            */
/* 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 <sqlite3.h>

#include "Template.h"
#include "template_syntax.h"

#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdio>

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

Template::~Template()
{
    multimap<string,Attribute *>::iterator  it;

    for ( it = attributes.begin(); it != attributes.end(); it++)
    {
        delete it->second;
    }
}

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

pthread_mutex_t Template::mutex = PTHREAD_MUTEX_INITIALIZER;

extern "C"
{
    typedef struct yy_buffer_state * YY_BUFFER_STATE;

    extern FILE *template_in, *template_out;

    int template_parse(Template * tmpl, char ** errmsg);

    int template_lex_destroy();

    YY_BUFFER_STATE template__scan_string(const char * str);

    void template__delete_buffer(YY_BUFFER_STATE);
}

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

int Template::parse(const char * filename, char **error_msg)
{
    int     rc;

    pthread_mutex_lock(&mutex);

    *error_msg = 0;

    template_in = fopen (filename, "r");

    if ( template_in == 0 )
    {
        goto error_open;
    }

    rc = template_parse(this,error_msg);

    fclose(template_in);

    template_lex_destroy();

    pthread_mutex_unlock(&mutex);

    return rc;

error_open:
    *error_msg = strdup("Error opening template file");

    pthread_mutex_unlock(&mutex);

    return -1;
}

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

int Template::parse(const string &parse_str, char **error_msg)
{
    YY_BUFFER_STATE     str_buffer = 0;
    const char *        str;
    int                 rc;

    pthread_mutex_lock(&mutex);

    *error_msg = 0;

    str = parse_str.c_str();

    str_buffer = template__scan_string(str);

    if (str_buffer == 0)
    {
        goto error_yy;
    }

    rc = template_parse(this,error_msg);

    template__delete_buffer(str_buffer);

    template_lex_destroy();

    pthread_mutex_unlock(&mutex);

    return rc;

error_yy:

    *error_msg=strdup("Error setting scan buffer");

    pthread_mutex_unlock(&mutex);

    return -1;
}

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

void Template::marshall(string &str, const char delim)
{
    multimap<string,Attribute *>::iterator  it;
    string *                                attr;

    for(it=attributes.begin(),str="";it!=attributes.end();it++)
    {
        attr = it->second->marshall();

        if ( attr == 0 )
        {
            continue;
        }

        str += it->first + "=" + *attr + delim;

        delete attr;
    }
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void Template::set(Attribute * attr)
{
    if ( replace_mode == true )
    {
        multimap<string, Attribute *>::iterator         i;
        pair<multimap<string, Attribute *>::iterator,
        multimap<string, Attribute *>::iterator>        index;

        index = attributes.equal_range(attr->name());

        for ( i = index.first; i != index.second; i++)
        {
            delete i->second;
        }

        attributes.erase(attr->name());
    }

    attributes.insert(make_pair(attr->name(),attr));
};

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

int Template::remove(const string& name, vector<Attribute *>& values)
{
    multimap<string, Attribute *>::iterator         i;
    pair<multimap<string, Attribute *>::iterator,
    multimap<string, Attribute *>::iterator>        index;
    int                                             j;

    index = attributes.equal_range(name);

    for ( i = index.first,j=0 ; i != index.second ; i++,j++ )
    {
        values.push_back(i->second);
    }

    attributes.erase(index.first,index.second);

    return j;
}

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

int Template::erase(const string& name)
{
    multimap<string, Attribute *>::iterator         i;

    pair<
        multimap<string, Attribute *>::iterator,
        multimap<string, Attribute *>::iterator
        >                                           index;
    int                                             j;

    index = attributes.equal_range(name);

    for ( i = index.first,j=0 ; i != index.second ; i++,j++ )
    {
        Attribute * attr = i->second;
        delete attr;
    }

    attributes.erase(index.first,index.second);

    return j;

}

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

int Template::get(
    const string& name,
    vector<const Attribute*>& values) const
{
    multimap<string, Attribute *>::const_iterator       i;
    pair<multimap<string, Attribute *>::const_iterator,
    multimap<string, Attribute *>::const_iterator>      index;
    int                                                 j;

    index = attributes.equal_range(name);

    for ( i = index.first,j=0 ; i != index.second ; i++,j++ )
    {
        values.push_back(i->second);
    }

    return j;
}

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

int Template::get(
    const string& name,
    vector<Attribute*>& values)
{
    multimap<string, Attribute *>::iterator       i;
    pair<multimap<string, Attribute *>::iterator,
    multimap<string, Attribute *>::iterator>      index;
    int                                           j;

    index = attributes.equal_range(name);

    for ( i = index.first,j=0 ; i != index.second ; i++,j++ )
    {
        values.push_back(i->second);
    }

    return j;
}

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

void Template::get(
        string& name,
        string& value) const
{
    vector<const Attribute *>   attrs;
    const SingleAttribute *     sattr;
    int                         rc;

    transform (name.begin(),name.end(),name.begin(),(int(*)(int))toupper);

    rc = get(name,attrs);

    if  (rc == 0)
    {
        value = "";
        return;
    }

    sattr = dynamic_cast<const SingleAttribute *>(attrs[0]);

    if ( sattr != 0 )
    {
        value = sattr->value();
    }
    else
    {
        value="";
    }
}

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

void Template::get(
        string& name,
        int&    value) const
{
    string sval;

    get(name, sval);

    if ( sval == "" )
    {
        value = 0;
        return;
    }

    istringstream iss(sval);

    iss >> value;
}

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

string& Template::to_xml(string& xml) const
{
    multimap<string,Attribute *>::const_iterator  it;
    ostringstream                   		oss;
    string *                                s;

    oss << "<" << xml_root << ">";

    for ( it = attributes.begin(); it!=attributes.end(); it++)
    {
        s = it->second->to_xml();

        oss << *s;

        delete s;
    }

    oss << "</" << xml_root << ">";

    xml = oss.str();

	return xml;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

string& Template::to_str(string& str) const
{
	ostringstream os;
    multimap<string,Attribute *>::const_iterator  it;
    string *                                s;

    for ( it = attributes.begin(); it!=attributes.end(); it++)
    {
        s = it->second->marshall(",");

        os << endl << "\t" << it->first << separator << *s;

        delete s;
    }

	str = os.str();
    return str;
}

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

ostream& operator << (ostream& os, const Template& t)
{
	string str;

	os << t.to_str(str);

    return os;
}

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

Attribute * Template::single_xml_att(const xmlNode * node)
{
    Attribute * attr = 0;
    xmlNode *   child = node->children;

    if( child != 0 && (child->type == XML_TEXT_NODE ||
                       child->type == XML_CDATA_SECTION_NODE))
    {
        attr = new SingleAttribute(
                            reinterpret_cast<const char *>(node->name),
                            reinterpret_cast<const char *>(child->content) );
    }

    return attr;
}

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

Attribute * Template::vector_xml_att(const xmlNode * node)
{
    VectorAttribute *   attr        = 0;

    xmlNode *           child       = node->children;
    xmlNode *           grandchild  = 0;

    if(child != 0 && child->type == XML_ELEMENT_NODE)
    {
        attr = new VectorAttribute(
                        reinterpret_cast<const char *>(node->name));

        for(child = child; child != 0; child = child->next)
        {
            grandchild = child->children;

            if( grandchild != 0 && (grandchild->type == XML_TEXT_NODE ||
                                    grandchild->type == XML_CDATA_SECTION_NODE))
            {
                attr->replace(
                        reinterpret_cast<const char *>(child->name),
                        reinterpret_cast<const char *>(grandchild->content) );
            }
        }
    }

    return attr;
}

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

int Template::from_xml(const string &xml_str)
{
    xmlDocPtr xml_doc = 0;

    xmlNode * root_element;
    xmlNode * cur_node = 0;

    Attribute * attr;

    // Parse xml string as libxml document
    xml_doc = xmlParseMemory (xml_str.c_str(),xml_str.length());

    if (xml_doc == 0) // Error parsing XML Document
    {
        return -1;
    }

    // Get the <TEMPLATE> element
    root_element = xmlDocGetRootElement(xml_doc);

    // Get the root's children and try to build attributes.
    for (cur_node = root_element->children;
         cur_node != 0;
         cur_node = cur_node->next)
    {
        if (cur_node->type == XML_ELEMENT_NODE)
        {
            // Try to build a single attr.
            attr = single_xml_att(cur_node);
            if(attr == 0)   // The xml element wasn't a single attr.
            {
                // Try with a vector attr.
                attr = vector_xml_att(cur_node);
            }

            if(attr != 0)
            {
                set(attr);
            }
        }
    }

    xmlFreeDoc(xml_doc);

    return 0;
}

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

<commit_msg>feature #282: clear the template before re-build<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org)             */
/*                                                                            */
/* 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 <sqlite3.h>

#include "Template.h"
#include "template_syntax.h"

#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdio>

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

Template::~Template()
{
    multimap<string,Attribute *>::iterator  it;

    for ( it = attributes.begin(); it != attributes.end(); it++)
    {
        delete it->second;
    }
}

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

pthread_mutex_t Template::mutex = PTHREAD_MUTEX_INITIALIZER;

extern "C"
{
    typedef struct yy_buffer_state * YY_BUFFER_STATE;

    extern FILE *template_in, *template_out;

    int template_parse(Template * tmpl, char ** errmsg);

    int template_lex_destroy();

    YY_BUFFER_STATE template__scan_string(const char * str);

    void template__delete_buffer(YY_BUFFER_STATE);
}

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

int Template::parse(const char * filename, char **error_msg)
{
    int     rc;

    pthread_mutex_lock(&mutex);

    *error_msg = 0;

    template_in = fopen (filename, "r");

    if ( template_in == 0 )
    {
        goto error_open;
    }

    rc = template_parse(this,error_msg);

    fclose(template_in);

    template_lex_destroy();

    pthread_mutex_unlock(&mutex);

    return rc;

error_open:
    *error_msg = strdup("Error opening template file");

    pthread_mutex_unlock(&mutex);

    return -1;
}

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

int Template::parse(const string &parse_str, char **error_msg)
{
    YY_BUFFER_STATE     str_buffer = 0;
    const char *        str;
    int                 rc;

    pthread_mutex_lock(&mutex);

    *error_msg = 0;

    str = parse_str.c_str();

    str_buffer = template__scan_string(str);

    if (str_buffer == 0)
    {
        goto error_yy;
    }

    rc = template_parse(this,error_msg);

    template__delete_buffer(str_buffer);

    template_lex_destroy();

    pthread_mutex_unlock(&mutex);

    return rc;

error_yy:

    *error_msg=strdup("Error setting scan buffer");

    pthread_mutex_unlock(&mutex);

    return -1;
}

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

void Template::marshall(string &str, const char delim)
{
    multimap<string,Attribute *>::iterator  it;
    string *                                attr;

    for(it=attributes.begin(),str="";it!=attributes.end();it++)
    {
        attr = it->second->marshall();

        if ( attr == 0 )
        {
            continue;
        }

        str += it->first + "=" + *attr + delim;

        delete attr;
    }
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void Template::set(Attribute * attr)
{
    if ( replace_mode == true )
    {
        multimap<string, Attribute *>::iterator         i;
        pair<multimap<string, Attribute *>::iterator,
        multimap<string, Attribute *>::iterator>        index;

        index = attributes.equal_range(attr->name());

        for ( i = index.first; i != index.second; i++)
        {
            delete i->second;
        }

        attributes.erase(attr->name());
    }

    attributes.insert(make_pair(attr->name(),attr));
};

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

int Template::remove(const string& name, vector<Attribute *>& values)
{
    multimap<string, Attribute *>::iterator         i;
    pair<multimap<string, Attribute *>::iterator,
    multimap<string, Attribute *>::iterator>        index;
    int                                             j;

    index = attributes.equal_range(name);

    for ( i = index.first,j=0 ; i != index.second ; i++,j++ )
    {
        values.push_back(i->second);
    }

    attributes.erase(index.first,index.second);

    return j;
}

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

int Template::erase(const string& name)
{
    multimap<string, Attribute *>::iterator         i;

    pair<
        multimap<string, Attribute *>::iterator,
        multimap<string, Attribute *>::iterator
        >                                           index;
    int                                             j;

    index = attributes.equal_range(name);

    for ( i = index.first,j=0 ; i != index.second ; i++,j++ )
    {
        Attribute * attr = i->second;
        delete attr;
    }

    attributes.erase(index.first,index.second);

    return j;

}

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

int Template::get(
    const string& name,
    vector<const Attribute*>& values) const
{
    multimap<string, Attribute *>::const_iterator       i;
    pair<multimap<string, Attribute *>::const_iterator,
    multimap<string, Attribute *>::const_iterator>      index;
    int                                                 j;

    index = attributes.equal_range(name);

    for ( i = index.first,j=0 ; i != index.second ; i++,j++ )
    {
        values.push_back(i->second);
    }

    return j;
}

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

int Template::get(
    const string& name,
    vector<Attribute*>& values)
{
    multimap<string, Attribute *>::iterator       i;
    pair<multimap<string, Attribute *>::iterator,
    multimap<string, Attribute *>::iterator>      index;
    int                                           j;

    index = attributes.equal_range(name);

    for ( i = index.first,j=0 ; i != index.second ; i++,j++ )
    {
        values.push_back(i->second);
    }

    return j;
}

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

void Template::get(
        string& name,
        string& value) const
{
    vector<const Attribute *>   attrs;
    const SingleAttribute *     sattr;
    int                         rc;

    transform (name.begin(),name.end(),name.begin(),(int(*)(int))toupper);

    rc = get(name,attrs);

    if  (rc == 0)
    {
        value = "";
        return;
    }

    sattr = dynamic_cast<const SingleAttribute *>(attrs[0]);

    if ( sattr != 0 )
    {
        value = sattr->value();
    }
    else
    {
        value="";
    }
}

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

void Template::get(
        string& name,
        int&    value) const
{
    string sval;

    get(name, sval);

    if ( sval == "" )
    {
        value = 0;
        return;
    }

    istringstream iss(sval);

    iss >> value;
}

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

string& Template::to_xml(string& xml) const
{
    multimap<string,Attribute *>::const_iterator  it;
    ostringstream                   		oss;
    string *                                s;

    oss << "<" << xml_root << ">";

    for ( it = attributes.begin(); it!=attributes.end(); it++)
    {
        s = it->second->to_xml();

        oss << *s;

        delete s;
    }

    oss << "</" << xml_root << ">";

    xml = oss.str();

	return xml;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

string& Template::to_str(string& str) const
{
	ostringstream os;
    multimap<string,Attribute *>::const_iterator  it;
    string *                                s;

    for ( it = attributes.begin(); it!=attributes.end(); it++)
    {
        s = it->second->marshall(",");

        os << endl << "\t" << it->first << separator << *s;

        delete s;
    }

	str = os.str();
    return str;
}

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

ostream& operator << (ostream& os, const Template& t)
{
	string str;

	os << t.to_str(str);

    return os;
}

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

Attribute * Template::single_xml_att(const xmlNode * node)
{
    Attribute * attr = 0;
    xmlNode *   child = node->children;

    if( child != 0 && (child->type == XML_TEXT_NODE ||
                       child->type == XML_CDATA_SECTION_NODE))
    {
        attr = new SingleAttribute(
                            reinterpret_cast<const char *>(node->name),
                            reinterpret_cast<const char *>(child->content) );
    }

    return attr;
}

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

Attribute * Template::vector_xml_att(const xmlNode * node)
{
    VectorAttribute *   attr        = 0;

    xmlNode *           child       = node->children;
    xmlNode *           grandchild  = 0;

    if(child != 0 && child->type == XML_ELEMENT_NODE)
    {
        attr = new VectorAttribute(
                        reinterpret_cast<const char *>(node->name));

        for(child = child; child != 0; child = child->next)
        {
            grandchild = child->children;

            if( grandchild != 0 && (grandchild->type == XML_TEXT_NODE ||
                                    grandchild->type == XML_CDATA_SECTION_NODE))
            {
                attr->replace(
                        reinterpret_cast<const char *>(child->name),
                        reinterpret_cast<const char *>(grandchild->content) );
            }
        }
    }

    return attr;
}

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

int Template::from_xml(const string &xml_str)
{
    xmlDocPtr xml_doc = 0;

    xmlNode * root_element;
    xmlNode * cur_node = 0;

    Attribute * attr;

    // Parse xml string as libxml document
    xml_doc = xmlParseMemory (xml_str.c_str(),xml_str.length());

    if (xml_doc == 0) // Error parsing XML Document
    {
        return -1;
    }

    //Clear the template if not empty
    if (!attributes.empty())
    {
        multimap<string,Attribute *>::iterator  it;

        for ( it = attributes.begin(); it != attributes.end(); it++)
        {
            delete it->second;
        }

        attributes.clear();
    }

    // Get the <TEMPLATE> element
    root_element = xmlDocGetRootElement(xml_doc);

    // Get the root's children and try to build attributes.
    for (cur_node = root_element->children;
         cur_node != 0;
         cur_node = cur_node->next)
    {
        if (cur_node->type == XML_ELEMENT_NODE)
        {
            // Try to build a single attr.
            attr = single_xml_att(cur_node);
            if(attr == 0)   // The xml element wasn't a single attr.
            {
                // Try with a vector attr.
                attr = vector_xml_att(cur_node);
            }

            if(attr != 0)
            {
                set(attr);
            }
        }
    }

    xmlFreeDoc(xml_doc);

    return 0;
}

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

<|endoftext|>