<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "OgreMaterialResource.h"
#include "OgreRenderingModule.h"

#include <Ogre.h>

namespace OgreRenderer
{
    OgreMaterialResource::OgreMaterialResource(const std::string& id) :
        ResourceInterface(id)
    {
    }

    OgreMaterialResource::OgreMaterialResource(const std::string& id, Foundation::AssetPtr source) :
        ResourceInterface(id)
    {
        SetData(source);
    }

    OgreMaterialResource::~OgreMaterialResource()
    {
        RemoveMaterial();
    }

    bool OgreMaterialResource::SetData(Foundation::AssetPtr source)
    {
        if (!source)
        {
            OgreRenderingModule::LogError("Null source asset data pointer");
            return false;
        }
        if (!source->GetSize())
        {
            OgreRenderingModule::LogError("Zero sized material asset");
            return false;
        }

        Ogre::DataStreamPtr data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(const_cast<Core::u8 *>(source->GetData()), source->GetSize()));
        Ogre::MaterialManager::getSingleton().parseScript(data, "");
        Ogre::MaterialManager::getSingleton().create(source->GetId(), "");

        OgreRenderingModule::LogDebug("Ogre material " + id_ + " created");
        return true;
    }

    static const std::string type_name("OgreMaterial");

    const std::string& OgreMaterialResource::GetType() const
    {
        return type_name;
    }

    const std::string& OgreMaterialResource::GetTypeStatic()
    {
        return type_name;
    }

    void OgreMaterialResource::RemoveMaterial()
    {
        if (!ogre_material_.isNull())
        {
            std::string material_name = ogre_material_->getName();
            ogre_material_.setNull();

            try
            {
                Ogre::MaterialManager::getSingleton().remove(material_name);
            }
            catch (...)
            {
                OgreRenderingModule::LogDebug("Warning: Ogre::MaterialManager::getSingleton().remove(material_name); failed in OgreMaterialResource.cpp.");
            }
        }
    }
}<commit_msg>Fixed a crash when trying to parse Ogre material, if the parsing failed for some reason.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "OgreMaterialResource.h"
#include "OgreRenderingModule.h"

#include <Ogre.h>

namespace OgreRenderer
{
    OgreMaterialResource::OgreMaterialResource(const std::string& id) :
        ResourceInterface(id)
    {
    }

    OgreMaterialResource::OgreMaterialResource(const std::string& id, Foundation::AssetPtr source) :
        ResourceInterface(id)
    {
        SetData(source);
    }

    OgreMaterialResource::~OgreMaterialResource()
    {
        RemoveMaterial();
    }

    bool OgreMaterialResource::SetData(Foundation::AssetPtr source)
    {
        if (!source)
        {
            OgreRenderingModule::LogError("Null source asset data pointer");
            return false;
        }
        if (!source->GetSize())
        {
            OgreRenderingModule::LogError("Zero sized material asset");
            return false;
        }

        Ogre::DataStreamPtr data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(const_cast<Core::u8 *>(source->GetData()), source->GetSize()));
        try
        {
            Ogre::MaterialManager::getSingleton().parseScript(data, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
            Ogre::MaterialManager::getSingleton().create(source->GetId(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);

            OgreRenderingModule::LogDebug("Ogre material " + id_ + " created");
        } catch (Ogre::Exception &e)
        {
            OgreRenderingModule::LogWarning(e.what());
            OgreRenderingModule::LogWarning("Failed to parse Ogre material " + id_ + ".");
        }
        return true;
    }

    static const std::string type_name("OgreMaterial");

    const std::string& OgreMaterialResource::GetType() const
    {
        return type_name;
    }

    const std::string& OgreMaterialResource::GetTypeStatic()
    {
        return type_name;
    }

    void OgreMaterialResource::RemoveMaterial()
    {
        if (!ogre_material_.isNull())
        {
            std::string material_name = ogre_material_->getName();
            ogre_material_.setNull();

            try
            {
                Ogre::MaterialManager::getSingleton().remove(material_name);
            }
            catch (...)
            {
                OgreRenderingModule::LogDebug("Warning: Ogre::MaterialManager::getSingleton().remove(material_name); failed in OgreMaterialResource.cpp.");
            }
        }
    }
}<|endoftext|>


<commit_before>#include "ItemManager.h"
#include <Items/ItemComponent.h>
#include <Items/ItemStackComponent.h>
#include <Game/GameSession.h>
#include <Game/ECS/GameWorld.h>
#include <Math/TransformSRT.h>

namespace DEM::RPG
{

CItemManager::CItemManager(Game::CGameSession& Owner) : _Session(Owner)
{
}
//---------------------------------------------------------------------

void CItemManager::GatherExistingTemplates()
{
	_Templates.clear();

	auto pWorld = _Session.FindFeature<Game::CGameWorld>();
	if (!pWorld) return;

	// All item templates live in no level (CStrID::Empty).
	// For iteration to work, no-level components must be validated before calling GatherExistingTemplates().
	pWorld->ForEachEntityInLevelWith<const CItemComponent>(CStrID::Empty,
		[this](auto EntityID, auto& Entity, const CItemComponent& Item)
	{
		if (Entity.TemplateID) _Templates.emplace(Entity.TemplateID, EntityID);

		//!!!if the same template is already prototyped, should delete duplicates and patch proto IDs in stacks!
	});

	//???really need? allows to process non-validated prototypes, but doesn't process ones without alive instances
	pWorld->ForEachComponent<const CItemStackComponent>([this, pWorld](auto EntityID, const CItemStackComponent& Stack)
	{
		if (!Stack.Prototype || Stack.Prototype == EntityID) return;

		const Game::CEntity* pProtoEntity = pWorld->GetEntity(Stack.Prototype);
		if (!pProtoEntity) return;

		if (pProtoEntity->TemplateID) _Templates.emplace(pProtoEntity->TemplateID, EntityID);
	});
}
//---------------------------------------------------------------------

Game::HEntity CItemManager::InternalCreateStack(Game::CGameWorld& World, CStrID LevelID, CStrID ItemID, U32 Count, Game::HEntity Container)
{
	Game::HEntity ProtoEntity;
	auto It = _Templates.find(ItemID);
	if (It == _Templates.cend())
	{
		// create prototype entity from template, validate components
	}
	else ProtoEntity = It->second;

	Game::HEntity StackEntity = World.CreateEntity(LevelID);
	auto pStack = World.AddComponent<CItemStackComponent>(StackEntity);
	if (!pStack)
	{
		World.DeleteEntity(StackEntity);
		return {};
	}

	pStack->Prototype = ProtoEntity;
	pStack->Count = Count;
	pStack->Container = Container;

	return StackEntity;
}
//---------------------------------------------------------------------

Game::HEntity CItemManager::CreateStack(CStrID ItemID, U32 Count, Game::HEntity Container)
{
	auto pWorld = _Session.FindFeature<Game::CGameWorld>();
	if (!pWorld) return {};

	const Game::CEntity* pContainerEntity = pWorld->GetEntity(Container);
	if (!pContainerEntity) return {};

	return InternalCreateStack(*pWorld, pContainerEntity->LevelID, ItemID, Count, Container);
}
//---------------------------------------------------------------------

Game::HEntity CItemManager::CreateStack(CStrID ItemID, U32 Count, CStrID LevelID, const Math::CTransformSRT& WorldTfm)
{
	auto pWorld = _Session.FindFeature<Game::CGameWorld>();
	if (!pWorld) return {};

	auto StackEntity = InternalCreateStack(*pWorld, LevelID, ItemID, Count, {});
	if (!StackEntity) return {};

	// add scene component! position an object!

	return StackEntity;
}
//---------------------------------------------------------------------

}
<commit_msg>Fixed incorrect entity ID<commit_after>#include "ItemManager.h"
#include <Items/ItemComponent.h>
#include <Items/ItemStackComponent.h>
#include <Game/GameSession.h>
#include <Game/ECS/GameWorld.h>
#include <Math/TransformSRT.h>

namespace DEM::RPG
{

CItemManager::CItemManager(Game::CGameSession& Owner) : _Session(Owner)
{
}
//---------------------------------------------------------------------

void CItemManager::GatherExistingTemplates()
{
	_Templates.clear();

	auto pWorld = _Session.FindFeature<Game::CGameWorld>();
	if (!pWorld) return;

	// All item templates live in no level (CStrID::Empty).
	// For iteration to work, no-level components must be validated before calling GatherExistingTemplates().
	pWorld->ForEachEntityInLevelWith<const CItemComponent>(CStrID::Empty,
		[this](auto EntityID, auto& Entity, const CItemComponent& Item)
	{
		if (Entity.TemplateID) _Templates.emplace(Entity.TemplateID, EntityID);

		//!!!if the same template is already prototyped, should delete duplicates and patch proto IDs in stacks!
	});

	//???really need? allows to process non-validated prototypes, but doesn't process ones without alive instances
	pWorld->ForEachComponent<const CItemStackComponent>([this, pWorld](auto EntityID, const CItemStackComponent& Stack)
	{
		if (!Stack.Prototype || Stack.Prototype == EntityID) return;

		const Game::CEntity* pProtoEntity = pWorld->GetEntity(Stack.Prototype);
		if (!pProtoEntity) return;

		if (pProtoEntity->TemplateID) _Templates.emplace(pProtoEntity->TemplateID, Stack.Prototype);
	});
}
//---------------------------------------------------------------------

Game::HEntity CItemManager::InternalCreateStack(Game::CGameWorld& World, CStrID LevelID, CStrID ItemID, U32 Count, Game::HEntity Container)
{
	Game::HEntity ProtoEntity;
	auto It = _Templates.find(ItemID);
	if (It == _Templates.cend())
	{
		// create prototype entity from template, validate components
	}
	else ProtoEntity = It->second;

	Game::HEntity StackEntity = World.CreateEntity(LevelID);
	auto pStack = World.AddComponent<CItemStackComponent>(StackEntity);
	if (!pStack)
	{
		World.DeleteEntity(StackEntity);
		return {};
	}

	pStack->Prototype = ProtoEntity;
	pStack->Count = Count;
	pStack->Container = Container;

	return StackEntity;
}
//---------------------------------------------------------------------

Game::HEntity CItemManager::CreateStack(CStrID ItemID, U32 Count, Game::HEntity Container)
{
	auto pWorld = _Session.FindFeature<Game::CGameWorld>();
	if (!pWorld) return {};

	const Game::CEntity* pContainerEntity = pWorld->GetEntity(Container);
	if (!pContainerEntity) return {};

	return InternalCreateStack(*pWorld, pContainerEntity->LevelID, ItemID, Count, Container);
}
//---------------------------------------------------------------------

Game::HEntity CItemManager::CreateStack(CStrID ItemID, U32 Count, CStrID LevelID, const Math::CTransformSRT& WorldTfm)
{
	auto pWorld = _Session.FindFeature<Game::CGameWorld>();
	if (!pWorld) return {};

	auto StackEntity = InternalCreateStack(*pWorld, LevelID, ItemID, Count, {});
	if (!StackEntity) return {};

	// add scene component! position an object!

	return StackEntity;
}
//---------------------------------------------------------------------

}
<|endoftext|>


<commit_before>/*!
 * This file is part of CameraPlus.
 *
 * Copyright (C) 2012-2014 Mohammed Sameer <msameer@foolab.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "qtcamconfig.h"
#include "qtcamimagesettings.h"
#include "qtcamvideosettings.h"
#include "qtcamresolution.h"
#include <QSettings>
#include <QStringList>
#include <QDebug>
#include <QMetaEnum>
#include <QFile>
#ifdef QT4
#include <QSystemDeviceInfo>
#else
#include <QDeviceInfo>
#endif
#include <cmath>

#ifndef DATA_DIR
#define DATA_DIR                              "/usr/share/qtcamera/config/"
#endif /* DATA_DIR */

#define CONFIGURATION_FILE                    QString("%1/qtcamera.ini")
#define RESOLUTIONS_FILE                      QString("%1/%2resolutions.ini")

static inline uint qHash(const QSize& size) {
  return qHash(QString("%1x%2").arg(size.width()).arg(size.height()));
}

class QtCamConfigPrivate {
public:
  QString element(const QString& name) const {
    return conf->value(QString("%1/element").arg(name)).toString();
  }

  QSize readResolution(const QString key) {
    QList<QString> parts = resolutions->value(key).toString().trimmed().split("x");
    return QSize(parts[0].toInt(), parts[1].toInt());
  }

  QVariant readWithFallback(const QString& generic, const QString& specific, const QString& key,
			    QSettings *settings = 0) {
    if (!settings) {
      settings = conf;
    }

    QString genericKey = QString("%1/%2").arg(generic).arg(key);
    QString specificKey = QString("%1/%2").arg(specific).arg(key);

    QVariant var = settings->value(genericKey);

    return settings->value(specificKey, var);
  }

  QSettings *conf;
  QSettings *resolutions;

  QList<QtCamResolution> readResolutions(const QtCamResolution::Mode& targetMode,
					 const QVariant& targetDevice) {
    QMap<float, QtCamResolution> res;

    foreach (const QString& id, resolutions->childGroups()) {
      resolutions->beginGroup(id);

      QSize capture = readResolution("capture");
      QSize preview = readResolution("preview");
      QSize viewfinder = readResolution("viewfinder");
      int fps = resolutions->value("fps").toInt();
      int nightFps = resolutions->value("night").toInt();
      int zslFps = resolutions->value("zsl").toInt();
      float megaPixels = capture.width() * capture.height();
      megaPixels = floor((megaPixels * 10) / (1000.0 * 1000.0)) / 10;

      QString aspectRatio = calculateAspectRatio(capture);
      QString commonName = QtCamConfigPrivate::commonName(capture);
      QVariant device = resolutions->value("device");

      QtCamResolution::Mode mode;
      QString m = resolutions->value("mode").toString();

      if (m == "image") {
	mode = QtCamResolution::ModeImage;
      }
      else if (m == "video") {
	mode = QtCamResolution::ModeVideo;
      }

      resolutions->endGroup();

      if (targetMode != mode || targetDevice != device) {
	continue;
      }

      QtCamResolution r(id, aspectRatio, capture, preview, viewfinder, fps, nightFps,
			zslFps, megaPixels, commonName, mode, device);
      if (r.isValid()) {
	res.insertMulti(-1 * megaPixels, r); // a trick to sort in reverse!
      }
    }

    return res.values();
  }

  QString calculateAspectRatio(const QSize& size) {
    if (m_ratios.isEmpty()) {
      m_ratios[1.3] = "4:3";
      m_ratios[1.5] = "3:2";
      m_ratios[1.6] = "16:10";
      m_ratios[1.7] = "16:9";
    }

    float r = (size.width() * 1.0) / size.height();
    r = floor(r * 10) / 10.0;

    for (QMap<float, QString>::const_iterator iter = m_ratios.constBegin();
	 iter != m_ratios.constEnd(); iter++) {
      if (qFuzzyCompare (r, iter.key())) {
	return iter.value();
      }
    }

    qWarning() << "calculateAspectRatio: unknown aspect ratio for size" << size;

    return QString("?:?");
  }

  QString commonName(const QSize& size) {
    if (m_names.isEmpty()) {
      m_names[QSize(1920, 1080)] = "1080p";
      m_names[QSize(1920, 1088)] = "1080p";
      m_names[QSize(1280, 720)] = "720p";
      m_names[QSize(640, 480)] = "VGA";
      m_names[QSize(848, 480)] = "WVGA"; // OK wikipedia lists it as wide PAL but WTH is wide PAL?
      m_names[QSize(800, 480)] = "WVGA";
      m_names[QSize(320, 240)] = "QVGA";
    }

    if (!m_names.contains(size)) {
      qWarning() << "commonName: unknown name for the resolution" << size;
      return QString("???");
    }

    return m_names[size];
  }

  QMap<float, QString> m_ratios;
  QHash<QSize, QString> m_names;
};

QtCamConfig::QtCamConfig(QObject *parent) :
  QObject(parent), d_ptr(new QtCamConfigPrivate) {

#ifdef QT4
  QString dev = QtMobility::QSystemDeviceInfo().model();
#else
  QString dev = QDeviceInfo().model();
#endif

  d_ptr->conf = new QSettings(CONFIGURATION_FILE.arg(dir()), QSettings::IniFormat, this);

  QString resolutions = RESOLUTIONS_FILE.arg(dir()).arg(dev.toLower() + "_");
  if (!QFile(resolutions).exists()) {
    resolutions = RESOLUTIONS_FILE.arg(dir()).arg(QString());
  }

  d_ptr->resolutions = new QSettings(resolutions, QSettings::IniFormat, this);
}

QtCamConfig::~QtCamConfig() {
  delete d_ptr;
}

QString QtCamConfig::dir() const {
  return QString::fromLocal8Bit(DATA_DIR);
}

QString QtCamConfig::deviceScannerType() const {
  return d_ptr->conf->value("devices/scanner").toString();
}

QString QtCamConfig::deviceScannerProperty() const {
  return d_ptr->conf->value("devices/property").toString();
}

QString QtCamConfig::videoSource() const {
  return d_ptr->element("video-source");
}

QString QtCamConfig::viewfinderSink() const {
  return d_ptr->element("viewfinder-sink");
}

QString QtCamConfig::viewfinderRenderer() const {
  return d_ptr->conf->value("viewfinder-sink/renderer").toString();
}

bool QtCamConfig::viewfinderUseFence() const {
  return d_ptr->conf->value("viewfinder-sink/use-fence").toBool();
}

QString QtCamConfig::audioSource() const {
  return d_ptr->element("audio-source");
}

QString QtCamConfig::wrapperVideoSource() const {
  return d_ptr->element("wrapper-video-source");
}

QString QtCamConfig::wrapperVideoSourceProperty() const {
  return d_ptr->conf->value("wrapper-video-source/property").toString();
}

QtCamImageSettings *QtCamConfig::imageSettings(const QVariant& id) {
  QString generic = "image";
  QString specific = QString("%1-%2").arg(generic).arg(id.toString());

  QString profileName = d_ptr->readWithFallback(generic, specific, "profile-name").toString();
  QString profilePath = d_ptr->readWithFallback(generic, specific, "profile-path").toString();
  QString suffix = d_ptr->readWithFallback(generic, specific, "extension").toString();

  QList<QtCamResolution> resolutions = d_ptr->readResolutions(QtCamResolution::ModeImage,
							      id);

  return new QtCamImageSettings(id.toString(), suffix, profileName, profilePath, resolutions);
}

QtCamVideoSettings *QtCamConfig::videoSettings(const QVariant& id) {
  QString generic = "video";
  QString specific = QString("%1-%2").arg(generic).arg(id.toString());

  QString profileName = d_ptr->readWithFallback(generic, specific, "profile-name").toString();
  QString profilePath = d_ptr->readWithFallback(generic, specific, "profile-path").toString();
  QString suffix = d_ptr->readWithFallback(generic, specific, "extension").toString();

  QList<QtCamResolution> resolutions = d_ptr->readResolutions(QtCamResolution::ModeVideo,
							      id);

  return new QtCamVideoSettings(id.toString(), suffix, profileName, profilePath, resolutions);
}

QString QtCamConfig::imageEncodingProfileName() const {
  return d_ptr->conf->value("image/profile-name").toString();
}

QString QtCamConfig::imageEncodingProfilePath() const {
  return d_ptr->conf->value("image/profile-path").toString();
}

QString QtCamConfig::videoEncodingProfileName() const {
  return d_ptr->conf->value("video/profile-name").toString();
}

QString QtCamConfig::videoEncodingProfilePath() const {
  return d_ptr->conf->value("video/profile-path").toString();
}

QString QtCamConfig::audioCaptureCaps() const {
  return d_ptr->conf->value("audio-capture-caps/caps").toString();
}

QString QtCamConfig::imageSuffix() const {
  return d_ptr->conf->value("image/extension").toString();
}

QString QtCamConfig::videoSuffix() const {
  return d_ptr->conf->value("video/extension").toString();
}

QStringList QtCamConfig::viewfinderFilters() const {
  return d_ptr->conf->value("viewfinder-filters/elements").toStringList();
}

bool QtCamConfig::viewfinderFiltersUseAnalysisBin() const {
  return d_ptr->conf->value("viewfinder-filters/use-analysis-bin").toBool();
}

QStringList QtCamConfig::imageFilters() const {
  return d_ptr->conf->value("image-filters/elements").toStringList();
}

bool QtCamConfig::imageFiltersUseAnalysisBin() const {
  return d_ptr->conf->value("image-filters/use-analysis-bin").toBool();
}

QString QtCamConfig::roiElement() const {
  return d_ptr->conf->value("roi/element").toString();
}

QString QtCamConfig::roiMessageName() const {
  return d_ptr->conf->value("roi/message").toString();
}

QString QtCamConfig::roiEnableProperty() const {
  return d_ptr->conf->value("roi/enable").toString();
}

QString QtCamConfig::roiMessage() const {
  return d_ptr->conf->value("roi/message").toString();
}

bool QtCamConfig::isPreviewSupported() const {
  return d_ptr->conf->value("general/preview-supported").toBool();
}

QString QtCamConfig::mediaType(const QString& id) const {
  return d_ptr->conf->value(QString("media-type/%1").arg(id)).toString();
}

QString QtCamConfig::mediaFourcc(const QString& id) const {
  return d_ptr->conf->value(QString("media-type/%1-fourcc").arg(id)).toString();
}

QString QtCamConfig::fastCaptureProperty() const {
  return d_ptr->conf->value("fast-capture/property").toString();
}
<commit_msg>modify how we lookup qtcamera.ini and resolutions.ini<commit_after>/*!
 * This file is part of CameraPlus.
 *
 * Copyright (C) 2012-2014 Mohammed Sameer <msameer@foolab.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "qtcamconfig.h"
#include "qtcamimagesettings.h"
#include "qtcamvideosettings.h"
#include "qtcamresolution.h"
#include <QSettings>
#include <QStringList>
#include <QDebug>
#include <QMetaEnum>
#include <QFile>
#ifdef QT4
#include <QSystemDeviceInfo>
#else
#include <QDeviceInfo>
#endif
#include <cmath>

#ifndef DATA_DIR
#define DATA_DIR                              "/usr/share/qtcamera/config/"
#endif /* DATA_DIR */

static inline uint qHash(const QSize& size) {
  return qHash(QString("%1x%2").arg(size.width()).arg(size.height()));
}

class QtCamConfigPrivate {
public:
  QString element(const QString& name) const {
    return conf->value(QString("%1/element").arg(name)).toString();
  }

  QSize readResolution(const QString key) {
    QList<QString> parts = resolutions->value(key).toString().trimmed().split("x");
    return QSize(parts[0].toInt(), parts[1].toInt());
  }

  QVariant readWithFallback(const QString& generic, const QString& specific, const QString& key,
			    QSettings *settings = 0) {
    if (!settings) {
      settings = conf;
    }

    QString genericKey = QString("%1/%2").arg(generic).arg(key);
    QString specificKey = QString("%1/%2").arg(specific).arg(key);

    QVariant var = settings->value(genericKey);

    return settings->value(specificKey, var);
  }

  QSettings *conf;
  QSettings *resolutions;

  QList<QtCamResolution> readResolutions(const QtCamResolution::Mode& targetMode,
					 const QVariant& targetDevice) {
    QMap<float, QtCamResolution> res;

    foreach (const QString& id, resolutions->childGroups()) {
      resolutions->beginGroup(id);

      QSize capture = readResolution("capture");
      QSize preview = readResolution("preview");
      QSize viewfinder = readResolution("viewfinder");
      int fps = resolutions->value("fps").toInt();
      int nightFps = resolutions->value("night").toInt();
      int zslFps = resolutions->value("zsl").toInt();
      float megaPixels = capture.width() * capture.height();
      megaPixels = floor((megaPixels * 10) / (1000.0 * 1000.0)) / 10;

      QString aspectRatio = calculateAspectRatio(capture);
      QString commonName = QtCamConfigPrivate::commonName(capture);
      QVariant device = resolutions->value("device");

      QtCamResolution::Mode mode;
      QString m = resolutions->value("mode").toString();

      if (m == "image") {
	mode = QtCamResolution::ModeImage;
      }
      else if (m == "video") {
	mode = QtCamResolution::ModeVideo;
      }

      resolutions->endGroup();

      if (targetMode != mode || targetDevice != device) {
	continue;
      }

      QtCamResolution r(id, aspectRatio, capture, preview, viewfinder, fps, nightFps,
			zslFps, megaPixels, commonName, mode, device);
      if (r.isValid()) {
	res.insertMulti(-1 * megaPixels, r); // a trick to sort in reverse!
      }
    }

    return res.values();
  }

  QString calculateAspectRatio(const QSize& size) {
    if (m_ratios.isEmpty()) {
      m_ratios[1.3] = "4:3";
      m_ratios[1.5] = "3:2";
      m_ratios[1.6] = "16:10";
      m_ratios[1.7] = "16:9";
    }

    float r = (size.width() * 1.0) / size.height();
    r = floor(r * 10) / 10.0;

    for (QMap<float, QString>::const_iterator iter = m_ratios.constBegin();
	 iter != m_ratios.constEnd(); iter++) {
      if (qFuzzyCompare (r, iter.key())) {
	return iter.value();
      }
    }

    qWarning() << "calculateAspectRatio: unknown aspect ratio for size" << size;

    return QString("?:?");
  }

  QString commonName(const QSize& size) {
    if (m_names.isEmpty()) {
      m_names[QSize(1920, 1080)] = "1080p";
      m_names[QSize(1920, 1088)] = "1080p";
      m_names[QSize(1280, 720)] = "720p";
      m_names[QSize(640, 480)] = "VGA";
      m_names[QSize(848, 480)] = "WVGA"; // OK wikipedia lists it as wide PAL but WTH is wide PAL?
      m_names[QSize(800, 480)] = "WVGA";
      m_names[QSize(320, 240)] = "QVGA";
    }

    if (!m_names.contains(size)) {
      qWarning() << "commonName: unknown name for the resolution" << size;
      return QString("???");
    }

    return m_names[size];
  }

  QMap<float, QString> m_ratios;
  QHash<QSize, QString> m_names;
};

QtCamConfig::QtCamConfig(QObject *parent) :
  QObject(parent),
  d_ptr(new QtCamConfigPrivate) {

#ifdef QT4
  QString dev = QtMobility::QSystemDeviceInfo().model().toLower();
#else
  QString dev = QDeviceInfo().model().toLower();
#endif

  QString confFile = QString("%1/%2/qtcamera.ini").arg(dir()).arg(dev);
  if (!QFile::exists(confFile)) {
    confFile = QString("%1/qtcamera.ini").arg(dir());
  }

  d_ptr->conf = new QSettings(confFile, QSettings::IniFormat, this);

  QString resolutions = QString("%1/%2/resolutions.ini").arg(dir()).arg(dev);
  if (!QFile(resolutions).exists()) {
    QString resolutions = QString("%1/resolutions.ini").arg(dir());
  }

  d_ptr->resolutions = new QSettings(resolutions, QSettings::IniFormat, this);
}

QtCamConfig::~QtCamConfig() {
  delete d_ptr;
}

QString QtCamConfig::dir() const {
  return QString::fromLocal8Bit(DATA_DIR);
}

QString QtCamConfig::deviceScannerType() const {
  return d_ptr->conf->value("devices/scanner").toString();
}

QString QtCamConfig::deviceScannerProperty() const {
  return d_ptr->conf->value("devices/property").toString();
}

QString QtCamConfig::videoSource() const {
  return d_ptr->element("video-source");
}

QString QtCamConfig::viewfinderSink() const {
  return d_ptr->element("viewfinder-sink");
}

QString QtCamConfig::viewfinderRenderer() const {
  return d_ptr->conf->value("viewfinder-sink/renderer").toString();
}

bool QtCamConfig::viewfinderUseFence() const {
  return d_ptr->conf->value("viewfinder-sink/use-fence").toBool();
}

QString QtCamConfig::audioSource() const {
  return d_ptr->element("audio-source");
}

QString QtCamConfig::wrapperVideoSource() const {
  return d_ptr->element("wrapper-video-source");
}

QString QtCamConfig::wrapperVideoSourceProperty() const {
  return d_ptr->conf->value("wrapper-video-source/property").toString();
}

QtCamImageSettings *QtCamConfig::imageSettings(const QVariant& id) {
  QString generic = "image";
  QString specific = QString("%1-%2").arg(generic).arg(id.toString());

  QString profileName = d_ptr->readWithFallback(generic, specific, "profile-name").toString();
  QString profilePath = d_ptr->readWithFallback(generic, specific, "profile-path").toString();
  QString suffix = d_ptr->readWithFallback(generic, specific, "extension").toString();

  QList<QtCamResolution> resolutions = d_ptr->readResolutions(QtCamResolution::ModeImage,
							      id);

  return new QtCamImageSettings(id.toString(), suffix, profileName, profilePath, resolutions);
}

QtCamVideoSettings *QtCamConfig::videoSettings(const QVariant& id) {
  QString generic = "video";
  QString specific = QString("%1-%2").arg(generic).arg(id.toString());

  QString profileName = d_ptr->readWithFallback(generic, specific, "profile-name").toString();
  QString profilePath = d_ptr->readWithFallback(generic, specific, "profile-path").toString();
  QString suffix = d_ptr->readWithFallback(generic, specific, "extension").toString();

  QList<QtCamResolution> resolutions = d_ptr->readResolutions(QtCamResolution::ModeVideo,
							      id);

  return new QtCamVideoSettings(id.toString(), suffix, profileName, profilePath, resolutions);
}

QString QtCamConfig::imageEncodingProfileName() const {
  return d_ptr->conf->value("image/profile-name").toString();
}

QString QtCamConfig::imageEncodingProfilePath() const {
  return d_ptr->conf->value("image/profile-path").toString();
}

QString QtCamConfig::videoEncodingProfileName() const {
  return d_ptr->conf->value("video/profile-name").toString();
}

QString QtCamConfig::videoEncodingProfilePath() const {
  return d_ptr->conf->value("video/profile-path").toString();
}

QString QtCamConfig::audioCaptureCaps() const {
  return d_ptr->conf->value("audio-capture-caps/caps").toString();
}

QString QtCamConfig::imageSuffix() const {
  return d_ptr->conf->value("image/extension").toString();
}

QString QtCamConfig::videoSuffix() const {
  return d_ptr->conf->value("video/extension").toString();
}

QStringList QtCamConfig::viewfinderFilters() const {
  return d_ptr->conf->value("viewfinder-filters/elements").toStringList();
}

bool QtCamConfig::viewfinderFiltersUseAnalysisBin() const {
  return d_ptr->conf->value("viewfinder-filters/use-analysis-bin").toBool();
}

QStringList QtCamConfig::imageFilters() const {
  return d_ptr->conf->value("image-filters/elements").toStringList();
}

bool QtCamConfig::imageFiltersUseAnalysisBin() const {
  return d_ptr->conf->value("image-filters/use-analysis-bin").toBool();
}

QString QtCamConfig::roiElement() const {
  return d_ptr->conf->value("roi/element").toString();
}

QString QtCamConfig::roiMessageName() const {
  return d_ptr->conf->value("roi/message").toString();
}

QString QtCamConfig::roiEnableProperty() const {
  return d_ptr->conf->value("roi/enable").toString();
}

QString QtCamConfig::roiMessage() const {
  return d_ptr->conf->value("roi/message").toString();
}

bool QtCamConfig::isPreviewSupported() const {
  return d_ptr->conf->value("general/preview-supported").toBool();
}

QString QtCamConfig::mediaType(const QString& id) const {
  return d_ptr->conf->value(QString("media-type/%1").arg(id)).toString();
}

QString QtCamConfig::mediaFourcc(const QString& id) const {
  return d_ptr->conf->value(QString("media-type/%1-fourcc").arg(id)).toString();
}

QString QtCamConfig::fastCaptureProperty() const {
  return d_ptr->conf->value("fast-capture/property").toString();
}
<|endoftext|>


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

#include <IconFontCppHeaders/IconsFontAwesome.h>
#include <Urho3D/Urho3DAll.h>
#include "ContentUtilities.h"

namespace Urho3D
{

const Vector<String> archiveExtensions_{".rar", ".zip", ".tar", ".gz", ".xz", ".7z", ".pak"};
const Vector<String> wordExtensions_{".doc", ".docx", ".odt"};
const Vector<String> codeExtensions_{".c", ".cpp", ".h", ".hpp", ".hxx", ".py", ".py3", ".js", ".cs"};
const Vector<String> imagesExtensions_{".png", ".jpg", ".jpeg", ".gif", ".ttf", ".dds", ".psd"};
const Vector<String> textExtensions_{".xml", ".json", ".txt"};
const Vector<String> audioExtensions_{".waw", ".ogg", ".mp3"};

FileType GetFileType(const String& fileName)
{
    auto extension = GetExtension(fileName).ToLower();
    if (archiveExtensions_.Contains(extension))
        return FTYPE_ARCHIVE;
    if (wordExtensions_.Contains(extension))
        return FTYPE_WORD;
    if (codeExtensions_.Contains(extension))
        return FTYPE_CODE;
    if (imagesExtensions_.Contains(extension))
        return FTYPE_IMAGE;
    if (textExtensions_.Contains(extension))
        return FTYPE_TEXT;
    if (audioExtensions_.Contains(extension))
        return FTYPE_AUDIO;
    if (extension == "pdf")
        return FTYPE_PDF;
    return FTYPE_FILE;
}

String GetFileIcon(const String& fileName)
{
    switch (GetFileType(fileName))
    {
    case FTYPE_ARCHIVE:
        return ICON_FA_FILE_ARCHIVE_O;
    case FTYPE_WORD:
        return ICON_FA_FILE_WORD_O;
    case FTYPE_CODE:
        return ICON_FA_FILE_CODE_O;
    case FTYPE_IMAGE:
        return ICON_FA_FILE_IMAGE_O;
    case FTYPE_PDF:
        return ICON_FA_FILE_PDF_O;
    case FTYPE_VIDEO:
        return ICON_FA_FILE_VIDEO_O;
    case FTYPE_POWERPOINT:
        return ICON_FA_FILE_POWERPOINT_O;
    case FTYPE_TEXT:
        return ICON_FA_FILE_TEXT_O;
    case FTYPE_FILM:
        return ICON_FA_FILE_VIDEO_O;
    case FTYPE_AUDIO:
        return ICON_FA_FILE_AUDIO_O;
    case FTYPE_EXCEL:
        return ICON_FA_FILE_EXCEL_O;
    default:
        return ICON_FA_FILE;
    }
}

ContentType GetContentType(const String& resourcePath)
{
    auto extension = GetExtension(resourcePath).ToLower();
    if (extension == ".xml")
    {
        auto systemUI = (SystemUI*)ui::GetIO().UserData;
        SharedPtr<XMLFile> xml(systemUI->GetCache()->GetResource<XMLFile>(resourcePath));
        auto rootElementName = xml->GetRoot().GetName();
        if (rootElementName == "scene")
            return CTYPE_SCENE;
        if (rootElementName == "node")
            return CTYPE_SCENEOBJECT;
        if (rootElementName == "elements")
            return CTYPE_UISTYLE;
        if (rootElementName == "element")
            return CTYPE_UILAYOUT;
        if (rootElementName == "material")
            return CTYPE_MATERIAL;
        if (rootElementName == "particleeffect")
            return CTYPE_PARTICLE;
        if (rootElementName == "renderpath")
            return CTYPE_RENDERPATH;
        if (rootElementName == "texture")
            return CTYPE_TEXTUREXML;
    }

    if (extension == ".mdl")
        return CTYPE_MODEL;
    if (extension == ".ani")
        return CTYPE_ANIMATION;
    if (audioExtensions_.Contains(extension))
        return CTYPE_SOUND;
    if (imagesExtensions_.Contains(extension))
        return CTYPE_TEXTURE;

    return CTYPE_UNKNOWN;
}

}
<commit_msg>Tools: GetContentType() understands .scene files.<commit_after>//
// Copyright (c) 2018 Rokas Kupstys
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#include <IconFontCppHeaders/IconsFontAwesome.h>
#include <Urho3D/Urho3DAll.h>
#include "ContentUtilities.h"

namespace Urho3D
{

const Vector<String> archiveExtensions_{".rar", ".zip", ".tar", ".gz", ".xz", ".7z", ".pak"};
const Vector<String> wordExtensions_{".doc", ".docx", ".odt"};
const Vector<String> codeExtensions_{".c", ".cpp", ".h", ".hpp", ".hxx", ".py", ".py3", ".js", ".cs"};
const Vector<String> imagesExtensions_{".png", ".jpg", ".jpeg", ".gif", ".ttf", ".dds", ".psd"};
const Vector<String> textExtensions_{".xml", ".json", ".txt"};
const Vector<String> audioExtensions_{".waw", ".ogg", ".mp3"};

FileType GetFileType(const String& fileName)
{
    auto extension = GetExtension(fileName).ToLower();
    if (archiveExtensions_.Contains(extension))
        return FTYPE_ARCHIVE;
    if (wordExtensions_.Contains(extension))
        return FTYPE_WORD;
    if (codeExtensions_.Contains(extension))
        return FTYPE_CODE;
    if (imagesExtensions_.Contains(extension))
        return FTYPE_IMAGE;
    if (textExtensions_.Contains(extension))
        return FTYPE_TEXT;
    if (audioExtensions_.Contains(extension))
        return FTYPE_AUDIO;
    if (extension == "pdf")
        return FTYPE_PDF;
    return FTYPE_FILE;
}

String GetFileIcon(const String& fileName)
{
    switch (GetFileType(fileName))
    {
    case FTYPE_ARCHIVE:
        return ICON_FA_FILE_ARCHIVE_O;
    case FTYPE_WORD:
        return ICON_FA_FILE_WORD_O;
    case FTYPE_CODE:
        return ICON_FA_FILE_CODE_O;
    case FTYPE_IMAGE:
        return ICON_FA_FILE_IMAGE_O;
    case FTYPE_PDF:
        return ICON_FA_FILE_PDF_O;
    case FTYPE_VIDEO:
        return ICON_FA_FILE_VIDEO_O;
    case FTYPE_POWERPOINT:
        return ICON_FA_FILE_POWERPOINT_O;
    case FTYPE_TEXT:
        return ICON_FA_FILE_TEXT_O;
    case FTYPE_FILM:
        return ICON_FA_FILE_VIDEO_O;
    case FTYPE_AUDIO:
        return ICON_FA_FILE_AUDIO_O;
    case FTYPE_EXCEL:
        return ICON_FA_FILE_EXCEL_O;
    default:
        return ICON_FA_FILE;
    }
}

ContentType GetContentType(const String& resourcePath)
{
    auto extension = GetExtension(resourcePath).ToLower();
    if (extension == ".xml")
    {
        auto systemUI = (SystemUI*)ui::GetIO().UserData;
        SharedPtr<XMLFile> xml(systemUI->GetCache()->GetResource<XMLFile>(resourcePath));
        auto rootElementName = xml->GetRoot().GetName();
        if (rootElementName == "scene")
            return CTYPE_SCENE;
        if (rootElementName == "node")
            return CTYPE_SCENEOBJECT;
        if (rootElementName == "elements")
            return CTYPE_UISTYLE;
        if (rootElementName == "element")
            return CTYPE_UILAYOUT;
        if (rootElementName == "material")
            return CTYPE_MATERIAL;
        if (rootElementName == "particleeffect")
            return CTYPE_PARTICLE;
        if (rootElementName == "renderpath")
            return CTYPE_RENDERPATH;
        if (rootElementName == "texture")
            return CTYPE_TEXTUREXML;
    }

    if (extension == ".mdl")
        return CTYPE_MODEL;
    if (extension == ".ani")
        return CTYPE_ANIMATION;
    if (extension == ".scene")
        return CTYPE_SCENE;
    if (audioExtensions_.Contains(extension))
        return CTYPE_SOUND;
    if (imagesExtensions_.Contains(extension))
        return CTYPE_TEXTURE;

    return CTYPE_UNKNOWN;
}

}
<|endoftext|>


<commit_before>/*
	This file is part of the E_MinSG library.
	Copyright (C) 2007-2012 Benjamin Eikel <benjamin@eikel.org>
	Copyright (C) 2007-2012 Claudius Jähn <claudius@uni-paderborn.de>
	Copyright (C) 2007-2012 Ralf Petring <ralf@petring.net>
	Copyright (C) 2021 Sascha Brandt <sascha@brandt.graphics>

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "E_PbrMaterialState.h"
#include "../../ELibMinSG.h"
#include "../ELibMinSGExt.h"
#include "../../Core/E_FrameContext.h"
#include <E_Rendering/Texture/E_Texture.h>
#include <E_Util/E_FileName.h>
#include <E_Util/IO/E_FileLocator.h>
#include <E_Util/E_Utils.h>
#include <E_Util/Graphics/E_Color.h>
#include <E_Geometry/E_Vec3.h>
#include <EScript/EScript.h>

using namespace EScript;
using namespace MinSG;

namespace E_MinSG {

Type* E_PbrMaterialState::typeObject=nullptr;

//! initMembers
void E_PbrMaterialState::init(EScript::Namespace & lib) {
	// E_PbrMaterialState ----|> E_State ----|> Object
	typeObject = new EScript::Type(E_State::getTypeObject());
	declareConstant(&lib,getClassName(),typeObject);
	addFactory<MinSG::PbrMaterialState,E_PbrMaterialState>();

	//! [ESMF] new MinSG.PbrMaterialState()
	ES_CTOR(typeObject,0,0,EScript::create( new PbrMaterialState))

	//! [ESMF] Number MinSG.PbrMaterialState.getBaseColorFactor()
	ES_MFUN(typeObject, const PbrMaterialState, "getBaseColorFactor", 0, 0, new E_Util::E_Color4f(thisObj->getBaseColorFactor()))

	//! [ESMF] thisEObj MinSG.PbrMaterialState.setBaseColorFactor(Number)
	ES_MFUN(typeObject, PbrMaterialState, "setBaseColorFactor", 1, 1, (thisObj->setBaseColorFactor(*parameter[0].to<Util::Color4f*>(rt)), thisEObj))

	//! [ESMF] Texture|Void MinSG.PbrMaterialState.getBaseColorTexture()
	ES_MFUN(typeObject, const PbrMaterialState, "getBaseColorTexture", 0, 0, new E_Rendering::E_Texture(thisObj->getBaseColorTexture()))

	//! [ESMF] thisEObj MinSG.PbrMaterialState.setBaseColorTexture(Texture)
	ES_MFUN(typeObject, PbrMaterialState, "setBaseColorTexture", 1, 1, (thisObj->setBaseColorTexture(!parameter[0].toBool() ? nullptr : parameter[0].to<Rendering::Texture*>(rt)), thisEObj))

	//! [ESMF] Texture|Void MinSG.PbrMaterialState.getMetallicRoughnessTexture()
	ES_MFUN(typeObject, const PbrMaterialState, "getMetallicRoughnessTexture", 0, 0, new E_Rendering::E_Texture(thisObj->getMetallicRoughnessTexture()))

	//! [ESMF] thisEObj MinSG.PbrMaterialState.setMetallicRoughnessTexture(Texture)
	ES_MFUN(typeObject, PbrMaterialState, "setMetallicRoughnessTexture", 1, 1, (thisObj->setMetallicRoughnessTexture(!parameter[0].toBool() ? nullptr : parameter[0].to<Rendering::Texture*>(rt)), thisEObj))

	//! [ESMF] Texture|Void MinSG.PbrMaterialState.getNormalTexture()
	ES_MFUN(typeObject, const PbrMaterialState, "getNormalTexture", 0, 0, new E_Rendering::E_Texture(thisObj->getNormalTexture()))

	//! [ESMF] thisEObj MinSG.PbrMaterialState.setNormalTexture(Texture)
	ES_MFUN(typeObject, PbrMaterialState, "setNormalTexture", 1, 1, (thisObj->setNormalTexture(!parameter[0].toBool() ? nullptr : parameter[0].to<Rendering::Texture*>(rt)), thisEObj))

	//! [ESMF] Texture|Void MinSG.PbrMaterialState.getOcclusionTexture()
	ES_MFUN(typeObject, const PbrMaterialState, "getOcclusionTexture", 0, 0, new E_Rendering::E_Texture(thisObj->getOcclusionTexture()))

	//! [ESMF] thisEObj MinSG.PbrMaterialState.setOcclusionTexture(Texture)
	ES_MFUN(typeObject, PbrMaterialState, "setOcclusionTexture", 1, 1, (thisObj->setOcclusionTexture(!parameter[0].toBool() ? nullptr : parameter[0].to<Rendering::Texture*>(rt)), thisEObj))

	//! [ESMF] Number MinSG.PbrMaterialState.getEmissiveFactor()
	ES_MFUN(typeObject, const PbrMaterialState, "getEmissiveFactor", 0, 0, new E_Geometry::E_Vec3(thisObj->getEmissiveFactor()))

	//! [ESMF] thisEObj MinSG.PbrMaterialState.setEmissiveFactor(Number)
	ES_MFUN(typeObject, PbrMaterialState, "setEmissiveFactor", 1, 1, (thisObj->setEmissiveFactor(parameter[0].to<const Geometry::Vec3&>(rt)), thisEObj))

	//! [ESMF] Texture|Void MinSG.PbrMaterialState.getEmissiveTexture()
	ES_MFUN(typeObject, const PbrMaterialState, "getEmissiveTexture", 0, 0, new E_Rendering::E_Texture(thisObj->getEmissiveTexture()))

	//! [ESMF] thisEObj MinSG.PbrMaterialState.setEmissiveTexture(Texture)
	ES_MFUN(typeObject, PbrMaterialState, "setEmissiveTexture", 1, 1, (thisObj->setEmissiveTexture(!parameter[0].toBool() ? nullptr : parameter[0].to<Rendering::Texture*>(rt)), thisEObj))

	//! [ESMF] Number MinSG.PbrMaterialState.getAlphaMode()
	ES_MFUN(typeObject, const PbrMaterialState, "getAlphaMode", 0, 0, static_cast<uint32_t>(thisObj->getAlphaMode()))

	//! [ESMF] thisEObj MinSG.PbrMaterialState.setAlphaMode(Number)
	ES_MFUN(typeObject, PbrMaterialState, "setAlphaMode", 1, 1, (thisObj->setAlphaMode(static_cast<PbrAlphaMode>(parameter[0].toUInt())), thisEObj))

	//! [ESMF] Number MinSG.PbrMaterialState.getShadingModel()
	ES_MFUN(typeObject, const PbrMaterialState, "getShadingModel", 0, 0, static_cast<uint32_t>(thisObj->getShadingModel()))

	//! [ESMF] thisEObj MinSG.PbrMaterialState.setShadingModel(Number)
	ES_MFUN(typeObject, PbrMaterialState, "setShadingModel", 1, 1, (thisObj->setShadingModel(static_cast<PbrShadingModel>(parameter[0].toUInt())), thisEObj))

	//! [ESMF] thisEObj MinSG.PbrMaterialState.setSearchPaths(FileLocator | Array)
	ES_MFUNCTION(typeObject, PbrMaterialState, "setSearchPaths", 1, 1, {
		auto* a = parameter[0].toType<EScript::Array>();
		if(a) {
			std::vector<std::string> paths;
			for(const auto& o : *a) {
				paths.emplace_back(o.toString());
			}
			thisObj->setSearchPaths(paths);
		} else {
			auto& locator = parameter[0].to<Util::FileLocator&>(rt);
			thisObj->setSearchPaths(locator.getSearchPaths());
		}
		return thisEObj;
	})

	ES_MGETSET(PbrMaterialState, uint32_t, BaseColorTexCoord)
	ES_MGETSET(PbrMaterialState, uint32_t, BaseColorTexUnit)
	ES_MGETSET(PbrMaterialState, float, MetallicFactor)
	ES_MGETSET(PbrMaterialState, float, RoughnessFactor)
	ES_MGETSET(PbrMaterialState, uint32_t, MetallicRoughnessTexCoord)
	ES_MGETSET(PbrMaterialState, uint32_t, MetallicRoughnessTexUnit)
	ES_MGETSET(PbrMaterialState, float, NormalScale)
	ES_MGETSET(PbrMaterialState, uint32_t, NormalTexCoord)
	ES_MGETSET(PbrMaterialState, uint32_t, NormalTexUnit)
	ES_MGETSET(PbrMaterialState, float, OcclusionStrength)
	ES_MGETSET(PbrMaterialState, uint32_t, OcclusionTexCoord)
	ES_MGETSET(PbrMaterialState, uint32_t, OcclusionTexUnit)
	ES_MGETSET(PbrMaterialState, uint32_t, EmissiveTexCoord)
	ES_MGETSET(PbrMaterialState, uint32_t, EmissiveTexUnit)
	ES_MGETSET(PbrMaterialState, float, AlphaCutoff)
	ES_MGETSET(PbrMaterialState, bool, DoubleSided)
	ES_MGETSET(PbrMaterialState, bool, UseSkinning)
	ES_MGETSET(PbrMaterialState, bool, UseIBL)
	ES_MGETSET(PbrMaterialState, bool, ReceiveShadow)
}
//---

//! [ctor]
E_PbrMaterialState::E_PbrMaterialState(PbrMaterialState * _obj, EScript::Type * type):
		E_State(_obj,type?type:typeObject){
}
//! [dtor]
E_PbrMaterialState::~E_PbrMaterialState(){
}

}
<commit_msg>fix when no textures attached to pbr material<commit_after>/*
	This file is part of the E_MinSG library.
	Copyright (C) 2007-2012 Benjamin Eikel <benjamin@eikel.org>
	Copyright (C) 2007-2012 Claudius Jähn <claudius@uni-paderborn.de>
	Copyright (C) 2007-2012 Ralf Petring <ralf@petring.net>
	Copyright (C) 2021 Sascha Brandt <sascha@brandt.graphics>

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "E_PbrMaterialState.h"
#include "../../ELibMinSG.h"
#include "../ELibMinSGExt.h"
#include "../../Core/E_FrameContext.h"
#include <E_Rendering/Texture/E_Texture.h>
#include <E_Util/E_FileName.h>
#include <E_Util/IO/E_FileLocator.h>
#include <E_Util/E_Utils.h>
#include <E_Util/Graphics/E_Color.h>
#include <E_Geometry/E_Vec3.h>
#include <EScript/EScript.h>

using namespace EScript;
using namespace MinSG;

namespace E_MinSG {

Type* E_PbrMaterialState::typeObject=nullptr;

//! initMembers
void E_PbrMaterialState::init(EScript::Namespace & lib) {
	// E_PbrMaterialState ----|> E_State ----|> Object
	typeObject = new EScript::Type(E_State::getTypeObject());
	declareConstant(&lib,getClassName(),typeObject);
	addFactory<MinSG::PbrMaterialState,E_PbrMaterialState>();

	//! [ESMF] new MinSG.PbrMaterialState()
	ES_CTOR(typeObject,0,0,EScript::create( new PbrMaterialState))

	//! [ESMF] Number MinSG.PbrMaterialState.getBaseColorFactor()
	ES_MFUN(typeObject, const PbrMaterialState, "getBaseColorFactor", 0, 0, new E_Util::E_Color4f(thisObj->getBaseColorFactor()))

	//! [ESMF] thisEObj MinSG.PbrMaterialState.setBaseColorFactor(Number)
	ES_MFUN(typeObject, PbrMaterialState, "setBaseColorFactor", 1, 1, (thisObj->setBaseColorFactor(*parameter[0].to<Util::Color4f*>(rt)), thisEObj))

	//! [ESMF] Texture|Void MinSG.PbrMaterialState.getBaseColorTexture()
	ES_MFUN(typeObject, const PbrMaterialState, "getBaseColorTexture", 0, 0, thisObj->getBaseColorTexture() ? new E_Rendering::E_Texture(thisObj->getBaseColorTexture()) : nullptr)

	//! [ESMF] thisEObj MinSG.PbrMaterialState.setBaseColorTexture(Texture)
	ES_MFUN(typeObject, PbrMaterialState, "setBaseColorTexture", 1, 1, (thisObj->setBaseColorTexture(!parameter[0].toBool() ? nullptr : parameter[0].to<Rendering::Texture*>(rt)), thisEObj))

	//! [ESMF] Texture|Void MinSG.PbrMaterialState.getMetallicRoughnessTexture()
	ES_MFUN(typeObject, const PbrMaterialState, "getMetallicRoughnessTexture", 0, 0, thisObj->getMetallicRoughnessTexture() ? new E_Rendering::E_Texture(thisObj->getMetallicRoughnessTexture()) : nullptr)

	//! [ESMF] thisEObj MinSG.PbrMaterialState.setMetallicRoughnessTexture(Texture)
	ES_MFUN(typeObject, PbrMaterialState, "setMetallicRoughnessTexture", 1, 1, (thisObj->setMetallicRoughnessTexture(!parameter[0].toBool() ? nullptr : parameter[0].to<Rendering::Texture*>(rt)), thisEObj))

	//! [ESMF] Texture|Void MinSG.PbrMaterialState.getNormalTexture()
	ES_MFUN(typeObject, const PbrMaterialState, "getNormalTexture", 0, 0, thisObj->getNormalTexture() ? new E_Rendering::E_Texture(thisObj->getNormalTexture()) : nullptr)

	//! [ESMF] thisEObj MinSG.PbrMaterialState.setNormalTexture(Texture)
	ES_MFUN(typeObject, PbrMaterialState, "setNormalTexture", 1, 1, (thisObj->setNormalTexture(!parameter[0].toBool() ? nullptr : parameter[0].to<Rendering::Texture*>(rt)), thisEObj))

	//! [ESMF] Texture|Void MinSG.PbrMaterialState.getOcclusionTexture()
	ES_MFUN(typeObject, const PbrMaterialState, "getOcclusionTexture", 0, 0, thisObj->getOcclusionTexture() ? new E_Rendering::E_Texture(thisObj->getOcclusionTexture()) : nullptr)

	//! [ESMF] thisEObj MinSG.PbrMaterialState.setOcclusionTexture(Texture)
	ES_MFUN(typeObject, PbrMaterialState, "setOcclusionTexture", 1, 1, (thisObj->setOcclusionTexture(!parameter[0].toBool() ? nullptr : parameter[0].to<Rendering::Texture*>(rt)), thisEObj))

	//! [ESMF] Number MinSG.PbrMaterialState.getEmissiveFactor()
	ES_MFUN(typeObject, const PbrMaterialState, "getEmissiveFactor", 0, 0, new E_Geometry::E_Vec3(thisObj->getEmissiveFactor()))

	//! [ESMF] thisEObj MinSG.PbrMaterialState.setEmissiveFactor(Number)
	ES_MFUN(typeObject, PbrMaterialState, "setEmissiveFactor", 1, 1, (thisObj->setEmissiveFactor(parameter[0].to<const Geometry::Vec3&>(rt)), thisEObj))

	//! [ESMF] Texture|Void MinSG.PbrMaterialState.getEmissiveTexture()
	ES_MFUN(typeObject, const PbrMaterialState, "getEmissiveTexture", 0, 0, thisObj->getEmissiveTexture() ? new E_Rendering::E_Texture(thisObj->getEmissiveTexture()) : nullptr)

	//! [ESMF] thisEObj MinSG.PbrMaterialState.setEmissiveTexture(Texture)
	ES_MFUN(typeObject, PbrMaterialState, "setEmissiveTexture", 1, 1, (thisObj->setEmissiveTexture(!parameter[0].toBool() ? nullptr : parameter[0].to<Rendering::Texture*>(rt)), thisEObj))

	//! [ESMF] Number MinSG.PbrMaterialState.getAlphaMode()
	ES_MFUN(typeObject, const PbrMaterialState, "getAlphaMode", 0, 0, static_cast<uint32_t>(thisObj->getAlphaMode()))

	//! [ESMF] thisEObj MinSG.PbrMaterialState.setAlphaMode(Number)
	ES_MFUN(typeObject, PbrMaterialState, "setAlphaMode", 1, 1, (thisObj->setAlphaMode(static_cast<PbrAlphaMode>(parameter[0].toUInt())), thisEObj))

	//! [ESMF] Number MinSG.PbrMaterialState.getShadingModel()
	ES_MFUN(typeObject, const PbrMaterialState, "getShadingModel", 0, 0, static_cast<uint32_t>(thisObj->getShadingModel()))

	//! [ESMF] thisEObj MinSG.PbrMaterialState.setShadingModel(Number)
	ES_MFUN(typeObject, PbrMaterialState, "setShadingModel", 1, 1, (thisObj->setShadingModel(static_cast<PbrShadingModel>(parameter[0].toUInt())), thisEObj))

	ES_MGETSET(PbrMaterialState, uint32_t, BaseColorTexCoord)
	ES_MGETSET(PbrMaterialState, uint32_t, BaseColorTexUnit)
	ES_MGETSET(PbrMaterialState, float, MetallicFactor)
	ES_MGETSET(PbrMaterialState, float, RoughnessFactor)
	ES_MGETSET(PbrMaterialState, uint32_t, MetallicRoughnessTexCoord)
	ES_MGETSET(PbrMaterialState, uint32_t, MetallicRoughnessTexUnit)
	ES_MGETSET(PbrMaterialState, float, NormalScale)
	ES_MGETSET(PbrMaterialState, uint32_t, NormalTexCoord)
	ES_MGETSET(PbrMaterialState, uint32_t, NormalTexUnit)
	ES_MGETSET(PbrMaterialState, float, OcclusionStrength)
	ES_MGETSET(PbrMaterialState, uint32_t, OcclusionTexCoord)
	ES_MGETSET(PbrMaterialState, uint32_t, OcclusionTexUnit)
	ES_MGETSET(PbrMaterialState, uint32_t, EmissiveTexCoord)
	ES_MGETSET(PbrMaterialState, uint32_t, EmissiveTexUnit)
	ES_MGETSET(PbrMaterialState, float, AlphaCutoff)
	ES_MGETSET(PbrMaterialState, bool, DoubleSided)
	ES_MGETSET(PbrMaterialState, bool, UseSkinning)
	ES_MGETSET(PbrMaterialState, bool, UseIBL)
	ES_MGETSET(PbrMaterialState, bool, ReceiveShadow)
}
//---

//! [ctor]
E_PbrMaterialState::E_PbrMaterialState(PbrMaterialState * _obj, EScript::Type * type):
		E_State(_obj,type?type:typeObject){
}
//! [dtor]
E_PbrMaterialState::~E_PbrMaterialState(){
}

}
<|endoftext|>


<commit_before>/*
 This file is part of cpp-ethereum.

 cpp-ethereum is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

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

 You should have received a copy of the GNU General Public License
 along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
 */
/** @file EC.cpp
 * @author Alex Leverington <nessence@gmail.com>
 * @date 2014
 *
 * Shared EC classes and functions.
 */

#pragma warning(push)
#pragma warning(disable:4100 4244)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wconversion"
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wdelete-non-virtual-dtor"
#pragma GCC diagnostic ignored "-Wextra"
#include <files.h>
#pragma warning(pop)
#pragma GCC diagnostic pop
#include "CryptoPP.h"
#include "SHA3.h"
#include "EC.h"

// CryptoPP and dev conflict so dev and pp namespace are used explicitly
using namespace std;
using namespace dev;
using namespace dev::crypto;
using namespace CryptoPP;

void crypto::encrypt(Public const& _key, bytes& io_cipher)
{
	ECIES<ECP>::Encryptor e;
	pp::initializeEncryptor(_key, e);
	size_t plen = io_cipher.size();
	bytes c;
	c.resize(e.CiphertextLength(plen));
	// todo: use StringSource with io_cipher as input and output.
	e.Encrypt(pp::PRNG, io_cipher.data(), plen, c.data());
	memset(io_cipher.data(), 0, io_cipher.size());
	io_cipher = std::move(c);
}

void crypto::decrypt(Secret const& _k, bytes& io_text)
{
	CryptoPP::ECIES<CryptoPP::ECP>::Decryptor d;
	pp::initializeDecryptor(_k, d);
	size_t clen = io_text.size();
	bytes p;
	p.resize(d.MaxPlaintextLength(io_text.size()));
	// todo: use StringSource with io_text as input and output.
	DecodingResult r = d.Decrypt(pp::PRNG, io_text.data(), clen, p.data());
	if (!r.isValidCoding)
	{
		io_text.clear();
		return;
	}
	io_text.resize(r.messageLength);
	io_text = std::move(p);
}

Signature crypto::sign(Secret const& _k, bytesConstRef _message)
{
	ECDSA<ECP, SHA3_256>::Signer signer;
	pp::initializeSigner(_k, signer);

	string sigstr;
	StringSource s(_message.toString(), true, new SignerFilter(pp::PRNG, signer, new StringSink(sigstr)));
	FixedHash<sizeof(Signature)> retsig((byte const*)sigstr.data(), Signature::ConstructFromPointer);
	return std::move(retsig);
}

bool crypto::verify(Public _p, Signature _sig, bytesConstRef _message, bool _raw)
{
	if (_raw)
	{
		assert(_message.size() == 32);
		byte encpub[65] = {0x04};
		memcpy(&encpub[1], _p.data(), 64);
		byte dersig[72];
		size_t cssz = DSAConvertSignatureFormat(dersig, 72, DSA_DER, _sig.data(), 64, DSA_P1363);
		assert(cssz <= 72);
		return (1 == secp256k1_ecdsa_verify(_message.data(), _message.size(), dersig, cssz, encpub, 65));
	}

	ECDSA<ECP, SHA3_256>::Verifier verifier;
	pp::initializeVerifier(_p, verifier);
	// cryptopp signatures are 64 bytes
	static_assert(sizeof(Signature) == 65, "Expected 65-byte signature.");
	return verifier.VerifyMessage(_message.data(), _message.size(), _sig.data(), sizeof(Signature) - 1);
}

<commit_msg>numbers to words<commit_after>/*
 This file is part of cpp-ethereum.

 cpp-ethereum is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

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

 You should have received a copy of the GNU General Public License
 along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
 */
/** @file EC.cpp
 * @author Alex Leverington <nessence@gmail.com>
 * @date 2014
 *
 * Shared EC classes and functions.
 */

#pragma warning(push)
#pragma warning(disable:4100 4244)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wconversion"
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wdelete-non-virtual-dtor"
#pragma GCC diagnostic ignored "-Wextra"
#include <files.h>
#pragma warning(pop)
#pragma GCC diagnostic pop
#include "CryptoPP.h"
#include "SHA3.h"
#include "EC.h"

// CryptoPP and dev conflict so dev and pp namespace are used explicitly
using namespace std;
using namespace dev;
using namespace dev::crypto;
using namespace CryptoPP;

void crypto::encrypt(Public const& _key, bytes& io_cipher)
{
	ECIES<ECP>::Encryptor e;
	pp::initializeEncryptor(_key, e);
	size_t plen = io_cipher.size();
	bytes c;
	c.resize(e.CiphertextLength(plen));
	// todo: use StringSource with io_cipher as input and output.
	e.Encrypt(pp::PRNG, io_cipher.data(), plen, c.data());
	memset(io_cipher.data(), 0, io_cipher.size());
	io_cipher = std::move(c);
}

void crypto::decrypt(Secret const& _k, bytes& io_text)
{
	CryptoPP::ECIES<CryptoPP::ECP>::Decryptor d;
	pp::initializeDecryptor(_k, d);
	size_t clen = io_text.size();
	bytes p;
	p.resize(d.MaxPlaintextLength(io_text.size()));
	// todo: use StringSource with io_text as input and output.
	DecodingResult r = d.Decrypt(pp::PRNG, io_text.data(), clen, p.data());
	if (!r.isValidCoding)
	{
		io_text.clear();
		return;
	}
	io_text.resize(r.messageLength);
	io_text = std::move(p);
}

Signature crypto::sign(Secret const& _k, bytesConstRef _message)
{
	ECDSA<ECP, SHA3_256>::Signer signer;
	pp::initializeSigner(_k, signer);

	string sigstr;
	StringSource s(_message.toString(), true, new SignerFilter(pp::PRNG, signer, new StringSink(sigstr)));
	FixedHash<sizeof(Signature)> retsig((byte const*)sigstr.data(), Signature::ConstructFromPointer);
	return std::move(retsig);
}

bool crypto::verify(Public _p, Signature _sig, bytesConstRef _message, bool _raw)
{
	static size_t derMaxEncodingLength = 72;
	if (_raw)
	{
		assert(_message.size() == 32);
		byte encpub[65] = {0x04};
		memcpy(&encpub[1], _p.data(), 64);
		byte dersig[derMaxEncodingLength];
		size_t cssz = DSAConvertSignatureFormat(dersig, derMaxEncodingLength, DSA_DER, _sig.data(), 64, DSA_P1363);
		assert(cssz <= derMaxEncodingLength);
		return (1 == secp256k1_ecdsa_verify(_message.data(), _message.size(), dersig, cssz, encpub, 65));
	}

	ECDSA<ECP, SHA3_256>::Verifier verifier;
	pp::initializeVerifier(_p, verifier);
	// cryptopp signatures are 64 bytes
	static_assert(sizeof(Signature) == 65, "Expected 65-byte signature.");
	return verifier.VerifyMessage(_message.data(), _message.size(), _sig.data(), sizeof(Signature) - 1);
}

<|endoftext|>


<commit_before>#include "Array.h"

#include "preprocessor/llvm_includes_start.h"
#include <llvm/IR/Module.h>
#include <llvm/IR/Function.h>
#include "preprocessor/llvm_includes_end.h"

#include "RuntimeManager.h"
#include "Runtime.h"
#include "Utils.h"

#include <set> // DEBUG only

namespace dev
{
namespace eth
{
namespace jit
{

static const auto c_reallocStep = 1;
static const auto c_reallocMultipier = 2;

llvm::Value* LazyFunction::call(llvm::IRBuilder<>& _builder, std::initializer_list<llvm::Value*> const& _args, llvm::Twine const& _name)
{
	if (!m_func)
		m_func = m_creator();

	return _builder.CreateCall(m_func, {_args.begin(), _args.size()}, _name);
}

llvm::Function* Array::createArrayPushFunc()
{
	llvm::Type* argTypes[] = {m_array->getType(), Type::Word};
	auto func = llvm::Function::Create(llvm::FunctionType::get(Type::Void, argTypes, false), llvm::Function::PrivateLinkage, "array.push", getModule());
	func->setDoesNotThrow();
	func->setDoesNotCapture(1);

	auto arrayPtr = &func->getArgumentList().front();
	arrayPtr->setName("arrayPtr");
	auto value = arrayPtr->getNextNode();
	value->setName("value");

	InsertPointGuard guard{m_builder};
	auto entryBB = llvm::BasicBlock::Create(m_builder.getContext(), "Entry", func);
	auto reallocBB = llvm::BasicBlock::Create(m_builder.getContext(), "Realloc", func);
	auto pushBB = llvm::BasicBlock::Create(m_builder.getContext(), "Push", func);

	m_builder.SetInsertPoint(entryBB);
	auto dataPtr = m_builder.CreateStructGEP(arrayPtr, 0, "dataPtr");
	auto sizePtr = m_builder.CreateStructGEP(arrayPtr, 1, "sizePtr");
	auto capPtr = m_builder.CreateStructGEP(arrayPtr, 2, "capPtr");
	auto data = m_builder.CreateLoad(dataPtr, "data");
	auto size = m_builder.CreateLoad(sizePtr, "size");
	auto cap = m_builder.CreateLoad(capPtr, "cap");
	auto reallocReq = m_builder.CreateICmpEQ(cap, size, "reallocReq");
	m_builder.CreateCondBr(reallocReq, reallocBB, pushBB);

	m_builder.SetInsertPoint(reallocBB);
	auto newCap = m_builder.CreateNUWAdd(cap, m_builder.getInt64(c_reallocStep), "newCap");
	//newCap = m_builder.CreateNUWMul(newCap, m_builder.getInt64(c_reallocMultipier));
	auto reallocSize = m_builder.CreateShl(newCap, 5, "reallocSize"); // size in bytes: newCap * 32
	auto bytes = m_builder.CreateBitCast(data, Type::BytePtr, "bytes");
	auto newBytes = m_reallocFunc.call(m_builder, {bytes, reallocSize}, "newBytes");
	auto newData = m_builder.CreateBitCast(newBytes, Type::WordPtr, "newData");
	m_builder.CreateStore(newData, dataPtr);
	m_builder.CreateStore(newCap, capPtr);
	m_builder.CreateBr(pushBB);

	m_builder.SetInsertPoint(pushBB);
	auto dataPhi = m_builder.CreatePHI(Type::WordPtr, 2, "dataPhi");
	dataPhi->addIncoming(data, entryBB);
	dataPhi->addIncoming(newData, reallocBB);
	auto newElemPtr = m_builder.CreateGEP(dataPhi, size, "newElemPtr");
	m_builder.CreateStore(value, newElemPtr);
	auto newSize = m_builder.CreateNUWAdd(size, m_builder.getInt64(1), "newSize");
	m_builder.CreateStore(newSize, sizePtr);
	m_builder.CreateRetVoid();

	return func;
}

llvm::Function* Array::createArraySetFunc()
{
	llvm::Type* argTypes[] = {m_array->getType(), Type::Size, Type::Word};
	auto func = llvm::Function::Create(llvm::FunctionType::get(Type::Void, argTypes, false), llvm::Function::PrivateLinkage, "array.set", getModule());
	func->setDoesNotThrow();
	func->setDoesNotCapture(1);

	auto arrayPtr = &func->getArgumentList().front();
	arrayPtr->setName("arrayPtr");
	auto index = arrayPtr->getNextNode();
	index->setName("index");
	auto value = index->getNextNode();
	value->setName("value");

	InsertPointGuard guard{m_builder};
	m_builder.SetInsertPoint(llvm::BasicBlock::Create(m_builder.getContext(), {}, func));
	auto dataPtr = m_builder.CreateStructGEP(arrayPtr, 0, "dataPtr");
	auto data = m_builder.CreateLoad(dataPtr, "data");
	auto valuePtr = m_builder.CreateGEP(data, index, "valuePtr");
	m_builder.CreateStore(value, valuePtr);
	m_builder.CreateRetVoid();
	return func;
}

llvm::Function* Array::createArrayGetFunc()
{
	llvm::Type* argTypes[] = {m_array->getType(), Type::Size};
	auto func = llvm::Function::Create(llvm::FunctionType::get(Type::Word, argTypes, false), llvm::Function::PrivateLinkage, "array.get", getModule());
	func->setDoesNotThrow();
	func->setDoesNotCapture(1);

	auto arrayPtr = &func->getArgumentList().front();
	arrayPtr->setName("arrayPtr");
	auto index = arrayPtr->getNextNode();
	index->setName("index");

	InsertPointGuard guard{m_builder};
	m_builder.SetInsertPoint(llvm::BasicBlock::Create(m_builder.getContext(), {}, func));
	auto dataPtr = m_builder.CreateStructGEP(arrayPtr, 0, "dataPtr");
	auto data = m_builder.CreateLoad(dataPtr, "data");
	auto valuePtr = m_builder.CreateGEP(data, index, "valuePtr");
	auto value = m_builder.CreateLoad(valuePtr, "value");
	m_builder.CreateRet(value);
	return func;
}

llvm::Function* Array::createGetPtrFunc()
{
	llvm::Type* argTypes[] = {m_array->getType(), Type::Size};
	auto func = llvm::Function::Create(llvm::FunctionType::get(Type::WordPtr, argTypes, false), llvm::Function::PrivateLinkage, "array.getPtr", getModule());
	func->setDoesNotThrow();
	func->setDoesNotCapture(1);

	auto arrayPtr = &func->getArgumentList().front();
	arrayPtr->setName("arrayPtr");
	auto index = arrayPtr->getNextNode();
	index->setName("index");

	InsertPointGuard guard{m_builder};
	m_builder.SetInsertPoint(llvm::BasicBlock::Create(m_builder.getContext(), {}, func));
	auto dataPtr = m_builder.CreateBitCast(arrayPtr, Type::BytePtr->getPointerTo(), "dataPtr");
	auto data = m_builder.CreateLoad(dataPtr, "data");
	auto bytePtr = m_builder.CreateGEP(data, index, "bytePtr");
	auto wordPtr = m_builder.CreateBitCast(bytePtr, Type::WordPtr, "wordPtr");
	m_builder.CreateRet(wordPtr);
	return func;
}

llvm::Function* Array::createFreeFunc()
{
	auto func = llvm::Function::Create(llvm::FunctionType::get(Type::Void, m_array->getType(), false), llvm::Function::PrivateLinkage, "array.free", getModule());
	func->setDoesNotThrow();
	func->setDoesNotCapture(1);

	auto freeFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, Type::BytePtr, false), llvm::Function::ExternalLinkage, "ext_free", getModule());
	freeFunc->setDoesNotThrow();
	freeFunc->setDoesNotCapture(1);

	auto arrayPtr = &func->getArgumentList().front();
	arrayPtr->setName("arrayPtr");

	InsertPointGuard guard{m_builder};
	m_builder.SetInsertPoint(llvm::BasicBlock::Create(m_builder.getContext(), {}, func));
	auto dataPtr = m_builder.CreateStructGEP(arrayPtr, 0, "dataPtr");
	auto data = m_builder.CreateLoad(dataPtr, "data");
	auto mem = m_builder.CreateBitCast(data, Type::BytePtr, "mem");
	m_builder.CreateCall(freeFunc, mem);
	m_builder.CreateRetVoid();
	return func;
}

llvm::Function* Array::getReallocFunc()
{
	if (auto func = getModule()->getFunction("ext_realloc"))
		return func;

	llvm::Type* reallocArgTypes[] = {Type::BytePtr, Type::Size};
	auto reallocFunc = llvm::Function::Create(llvm::FunctionType::get(Type::BytePtr, reallocArgTypes, false), llvm::Function::ExternalLinkage, "ext_realloc", getModule());
	reallocFunc->setDoesNotThrow();
	reallocFunc->setDoesNotAlias(0);
	reallocFunc->setDoesNotCapture(1);
	return reallocFunc;
}

llvm::Function* Array::createExtendFunc()
{
	llvm::Type* argTypes[] = {m_array->getType(), Type::Size};
	auto func = llvm::Function::Create(llvm::FunctionType::get(Type::Void, argTypes, false), llvm::Function::PrivateLinkage, "array.extend", getModule());
	func->setDoesNotThrow();
	func->setDoesNotCapture(1);

	auto arrayPtr = &func->getArgumentList().front();
	arrayPtr->setName("arrayPtr");
	auto newSize = arrayPtr->getNextNode();
	newSize->setName("newSize");

	InsertPointGuard guard{m_builder};
	m_builder.SetInsertPoint(llvm::BasicBlock::Create(m_builder.getContext(), {}, func));
	auto dataPtr = m_builder.CreateBitCast(arrayPtr, Type::BytePtr->getPointerTo(), "dataPtr");// TODO: Use byte* in Array
	auto sizePtr = m_builder.CreateStructGEP(arrayPtr, 1, "sizePtr");
	auto capPtr = m_builder.CreateStructGEP(arrayPtr, 2, "capPtr");
	auto data = m_builder.CreateLoad(dataPtr, "data");
	auto size = m_builder.CreateLoad(sizePtr, "size");
	auto extSize = m_builder.CreateNUWSub(newSize, size, "extSize");
	auto newData = m_reallocFunc.call(m_builder, {data, newSize}, "newData"); // TODO: Check realloc result for null
	auto extPtr = m_builder.CreateGEP(newData, size, "extPtr");
	m_builder.CreateMemSet(extPtr, m_builder.getInt8(0), extSize, 16);
	m_builder.CreateStore(newData, dataPtr);
	m_builder.CreateStore(newSize, sizePtr);
	m_builder.CreateStore(newSize, capPtr);
	m_builder.CreateRetVoid();
	return func;
}

llvm::Type* Array::getType()
{
	llvm::Type* elementTys[] = {Type::WordPtr, Type::Size, Type::Size};
	static auto arrayTy = llvm::StructType::create(elementTys, "Array");
	return arrayTy;
}

Array::Array(llvm::IRBuilder<>& _builder, char const* _name) :
	CompilerHelper(_builder),
	m_pushFunc([this](){ return createArrayPushFunc(); }),
	m_setFunc([this](){ return createArraySetFunc(); }),
	m_getFunc([this](){ return createArrayGetFunc(); }),
	m_freeFunc([this](){ return createFreeFunc(); })
{
	m_array = m_builder.CreateAlloca(getType(), nullptr, _name);
	m_builder.CreateStore(llvm::ConstantAggregateZero::get(getType()), m_array);
}

Array::Array(llvm::IRBuilder<>& _builder, llvm::Value* _array) :
	CompilerHelper(_builder),
	m_array(_array),
	m_pushFunc([this](){ return createArrayPushFunc(); }),
	m_setFunc([this](){ return createArraySetFunc(); }),
	m_getFunc([this](){ return createArrayGetFunc(); }),
	m_freeFunc([this](){ return createFreeFunc(); })
{
	m_builder.CreateStore(llvm::ConstantAggregateZero::get(getType()), m_array);
}

void Array::pop(llvm::Value* _count)
{
	auto sizePtr = m_builder.CreateStructGEP(m_array, 1, "sizePtr");
	auto size = m_builder.CreateLoad(sizePtr, "size");
	auto newSize = m_builder.CreateNUWSub(size, _count, "newSize");
	m_builder.CreateStore(newSize, sizePtr);
}

llvm::Value* Array::size(llvm::Value* _array)
{
	auto sizePtr = m_builder.CreateStructGEP(_array ? _array : m_array, 1, "sizePtr");
	return m_builder.CreateLoad(sizePtr, "array.size");
}

void Array::extend(llvm::Value* _arrayPtr, llvm::Value* _size)
{
	assert(_arrayPtr->getType() == m_array->getType());
	assert(_size->getType() == Type::Size);
	m_extendFunc.call(m_builder, {_arrayPtr, _size});
}

}
}
}

namespace
{
	struct AllocatedMemoryWatchdog
	{
		std::set<void*> allocatedMemory;

		~AllocatedMemoryWatchdog()
		{
			if (!allocatedMemory.empty())
			{
				DLOG(mem) << allocatedMemory.size() << " MEM LEAKS!\n";
				for (auto&& leak : allocatedMemory)
					DLOG(mem) << "\t" << leak << "\n";
			}
		}
	};

	AllocatedMemoryWatchdog watchdog;
}

extern "C"
{
	using namespace dev::eth::jit;

	EXPORT void* ext_realloc(void* _data, size_t _size) noexcept
	{
		//std::cerr << "REALLOC: " << _data << " [" << _size << "]" << std::endl;
		auto newData = std::realloc(_data, _size);
		if (_data != newData)
		{
			DLOG(mem) << "REALLOC: " << newData << " <- " << _data << " [" << _size << "]\n";
			watchdog.allocatedMemory.erase(_data);
			watchdog.allocatedMemory.insert(newData);
		}
		return newData;
	}

	EXPORT void ext_free(void* _data) noexcept
	{
		std::free(_data);
		if (_data)
		{
			DLOG(mem) << "FREE   : " << _data << "\n";
			watchdog.allocatedMemory.erase(_data);
		}
	}

} // extern "C"

<commit_msg>Remove memory leak detector. Is it not thread-safe.<commit_after>#include "Array.h"

#include "preprocessor/llvm_includes_start.h"
#include <llvm/IR/Module.h>
#include <llvm/IR/Function.h>
#include "preprocessor/llvm_includes_end.h"

#include "RuntimeManager.h"
#include "Runtime.h"
#include "Utils.h"

namespace dev
{
namespace eth
{
namespace jit
{

static const auto c_reallocStep = 1;
static const auto c_reallocMultipier = 2;

llvm::Value* LazyFunction::call(llvm::IRBuilder<>& _builder, std::initializer_list<llvm::Value*> const& _args, llvm::Twine const& _name)
{
	if (!m_func)
		m_func = m_creator();

	return _builder.CreateCall(m_func, {_args.begin(), _args.size()}, _name);
}

llvm::Function* Array::createArrayPushFunc()
{
	llvm::Type* argTypes[] = {m_array->getType(), Type::Word};
	auto func = llvm::Function::Create(llvm::FunctionType::get(Type::Void, argTypes, false), llvm::Function::PrivateLinkage, "array.push", getModule());
	func->setDoesNotThrow();
	func->setDoesNotCapture(1);

	auto arrayPtr = &func->getArgumentList().front();
	arrayPtr->setName("arrayPtr");
	auto value = arrayPtr->getNextNode();
	value->setName("value");

	InsertPointGuard guard{m_builder};
	auto entryBB = llvm::BasicBlock::Create(m_builder.getContext(), "Entry", func);
	auto reallocBB = llvm::BasicBlock::Create(m_builder.getContext(), "Realloc", func);
	auto pushBB = llvm::BasicBlock::Create(m_builder.getContext(), "Push", func);

	m_builder.SetInsertPoint(entryBB);
	auto dataPtr = m_builder.CreateStructGEP(arrayPtr, 0, "dataPtr");
	auto sizePtr = m_builder.CreateStructGEP(arrayPtr, 1, "sizePtr");
	auto capPtr = m_builder.CreateStructGEP(arrayPtr, 2, "capPtr");
	auto data = m_builder.CreateLoad(dataPtr, "data");
	auto size = m_builder.CreateLoad(sizePtr, "size");
	auto cap = m_builder.CreateLoad(capPtr, "cap");
	auto reallocReq = m_builder.CreateICmpEQ(cap, size, "reallocReq");
	m_builder.CreateCondBr(reallocReq, reallocBB, pushBB);

	m_builder.SetInsertPoint(reallocBB);
	auto newCap = m_builder.CreateNUWAdd(cap, m_builder.getInt64(c_reallocStep), "newCap");
	//newCap = m_builder.CreateNUWMul(newCap, m_builder.getInt64(c_reallocMultipier));
	auto reallocSize = m_builder.CreateShl(newCap, 5, "reallocSize"); // size in bytes: newCap * 32
	auto bytes = m_builder.CreateBitCast(data, Type::BytePtr, "bytes");
	auto newBytes = m_reallocFunc.call(m_builder, {bytes, reallocSize}, "newBytes");
	auto newData = m_builder.CreateBitCast(newBytes, Type::WordPtr, "newData");
	m_builder.CreateStore(newData, dataPtr);
	m_builder.CreateStore(newCap, capPtr);
	m_builder.CreateBr(pushBB);

	m_builder.SetInsertPoint(pushBB);
	auto dataPhi = m_builder.CreatePHI(Type::WordPtr, 2, "dataPhi");
	dataPhi->addIncoming(data, entryBB);
	dataPhi->addIncoming(newData, reallocBB);
	auto newElemPtr = m_builder.CreateGEP(dataPhi, size, "newElemPtr");
	m_builder.CreateStore(value, newElemPtr);
	auto newSize = m_builder.CreateNUWAdd(size, m_builder.getInt64(1), "newSize");
	m_builder.CreateStore(newSize, sizePtr);
	m_builder.CreateRetVoid();

	return func;
}

llvm::Function* Array::createArraySetFunc()
{
	llvm::Type* argTypes[] = {m_array->getType(), Type::Size, Type::Word};
	auto func = llvm::Function::Create(llvm::FunctionType::get(Type::Void, argTypes, false), llvm::Function::PrivateLinkage, "array.set", getModule());
	func->setDoesNotThrow();
	func->setDoesNotCapture(1);

	auto arrayPtr = &func->getArgumentList().front();
	arrayPtr->setName("arrayPtr");
	auto index = arrayPtr->getNextNode();
	index->setName("index");
	auto value = index->getNextNode();
	value->setName("value");

	InsertPointGuard guard{m_builder};
	m_builder.SetInsertPoint(llvm::BasicBlock::Create(m_builder.getContext(), {}, func));
	auto dataPtr = m_builder.CreateStructGEP(arrayPtr, 0, "dataPtr");
	auto data = m_builder.CreateLoad(dataPtr, "data");
	auto valuePtr = m_builder.CreateGEP(data, index, "valuePtr");
	m_builder.CreateStore(value, valuePtr);
	m_builder.CreateRetVoid();
	return func;
}

llvm::Function* Array::createArrayGetFunc()
{
	llvm::Type* argTypes[] = {m_array->getType(), Type::Size};
	auto func = llvm::Function::Create(llvm::FunctionType::get(Type::Word, argTypes, false), llvm::Function::PrivateLinkage, "array.get", getModule());
	func->setDoesNotThrow();
	func->setDoesNotCapture(1);

	auto arrayPtr = &func->getArgumentList().front();
	arrayPtr->setName("arrayPtr");
	auto index = arrayPtr->getNextNode();
	index->setName("index");

	InsertPointGuard guard{m_builder};
	m_builder.SetInsertPoint(llvm::BasicBlock::Create(m_builder.getContext(), {}, func));
	auto dataPtr = m_builder.CreateStructGEP(arrayPtr, 0, "dataPtr");
	auto data = m_builder.CreateLoad(dataPtr, "data");
	auto valuePtr = m_builder.CreateGEP(data, index, "valuePtr");
	auto value = m_builder.CreateLoad(valuePtr, "value");
	m_builder.CreateRet(value);
	return func;
}

llvm::Function* Array::createGetPtrFunc()
{
	llvm::Type* argTypes[] = {m_array->getType(), Type::Size};
	auto func = llvm::Function::Create(llvm::FunctionType::get(Type::WordPtr, argTypes, false), llvm::Function::PrivateLinkage, "array.getPtr", getModule());
	func->setDoesNotThrow();
	func->setDoesNotCapture(1);

	auto arrayPtr = &func->getArgumentList().front();
	arrayPtr->setName("arrayPtr");
	auto index = arrayPtr->getNextNode();
	index->setName("index");

	InsertPointGuard guard{m_builder};
	m_builder.SetInsertPoint(llvm::BasicBlock::Create(m_builder.getContext(), {}, func));
	auto dataPtr = m_builder.CreateBitCast(arrayPtr, Type::BytePtr->getPointerTo(), "dataPtr");
	auto data = m_builder.CreateLoad(dataPtr, "data");
	auto bytePtr = m_builder.CreateGEP(data, index, "bytePtr");
	auto wordPtr = m_builder.CreateBitCast(bytePtr, Type::WordPtr, "wordPtr");
	m_builder.CreateRet(wordPtr);
	return func;
}

llvm::Function* Array::createFreeFunc()
{
	auto func = llvm::Function::Create(llvm::FunctionType::get(Type::Void, m_array->getType(), false), llvm::Function::PrivateLinkage, "array.free", getModule());
	func->setDoesNotThrow();
	func->setDoesNotCapture(1);

	auto freeFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, Type::BytePtr, false), llvm::Function::ExternalLinkage, "ext_free", getModule());
	freeFunc->setDoesNotThrow();
	freeFunc->setDoesNotCapture(1);

	auto arrayPtr = &func->getArgumentList().front();
	arrayPtr->setName("arrayPtr");

	InsertPointGuard guard{m_builder};
	m_builder.SetInsertPoint(llvm::BasicBlock::Create(m_builder.getContext(), {}, func));
	auto dataPtr = m_builder.CreateStructGEP(arrayPtr, 0, "dataPtr");
	auto data = m_builder.CreateLoad(dataPtr, "data");
	auto mem = m_builder.CreateBitCast(data, Type::BytePtr, "mem");
	m_builder.CreateCall(freeFunc, mem);
	m_builder.CreateRetVoid();
	return func;
}

llvm::Function* Array::getReallocFunc()
{
	if (auto func = getModule()->getFunction("ext_realloc"))
		return func;

	llvm::Type* reallocArgTypes[] = {Type::BytePtr, Type::Size};
	auto reallocFunc = llvm::Function::Create(llvm::FunctionType::get(Type::BytePtr, reallocArgTypes, false), llvm::Function::ExternalLinkage, "ext_realloc", getModule());
	reallocFunc->setDoesNotThrow();
	reallocFunc->setDoesNotAlias(0);
	reallocFunc->setDoesNotCapture(1);
	return reallocFunc;
}

llvm::Function* Array::createExtendFunc()
{
	llvm::Type* argTypes[] = {m_array->getType(), Type::Size};
	auto func = llvm::Function::Create(llvm::FunctionType::get(Type::Void, argTypes, false), llvm::Function::PrivateLinkage, "array.extend", getModule());
	func->setDoesNotThrow();
	func->setDoesNotCapture(1);

	auto arrayPtr = &func->getArgumentList().front();
	arrayPtr->setName("arrayPtr");
	auto newSize = arrayPtr->getNextNode();
	newSize->setName("newSize");

	InsertPointGuard guard{m_builder};
	m_builder.SetInsertPoint(llvm::BasicBlock::Create(m_builder.getContext(), {}, func));
	auto dataPtr = m_builder.CreateBitCast(arrayPtr, Type::BytePtr->getPointerTo(), "dataPtr");// TODO: Use byte* in Array
	auto sizePtr = m_builder.CreateStructGEP(arrayPtr, 1, "sizePtr");
	auto capPtr = m_builder.CreateStructGEP(arrayPtr, 2, "capPtr");
	auto data = m_builder.CreateLoad(dataPtr, "data");
	auto size = m_builder.CreateLoad(sizePtr, "size");
	auto extSize = m_builder.CreateNUWSub(newSize, size, "extSize");
	auto newData = m_reallocFunc.call(m_builder, {data, newSize}, "newData"); // TODO: Check realloc result for null
	auto extPtr = m_builder.CreateGEP(newData, size, "extPtr");
	m_builder.CreateMemSet(extPtr, m_builder.getInt8(0), extSize, 16);
	m_builder.CreateStore(newData, dataPtr);
	m_builder.CreateStore(newSize, sizePtr);
	m_builder.CreateStore(newSize, capPtr);
	m_builder.CreateRetVoid();
	return func;
}

llvm::Type* Array::getType()
{
	llvm::Type* elementTys[] = {Type::WordPtr, Type::Size, Type::Size};
	static auto arrayTy = llvm::StructType::create(elementTys, "Array");
	return arrayTy;
}

Array::Array(llvm::IRBuilder<>& _builder, char const* _name) :
	CompilerHelper(_builder),
	m_pushFunc([this](){ return createArrayPushFunc(); }),
	m_setFunc([this](){ return createArraySetFunc(); }),
	m_getFunc([this](){ return createArrayGetFunc(); }),
	m_freeFunc([this](){ return createFreeFunc(); })
{
	m_array = m_builder.CreateAlloca(getType(), nullptr, _name);
	m_builder.CreateStore(llvm::ConstantAggregateZero::get(getType()), m_array);
}

Array::Array(llvm::IRBuilder<>& _builder, llvm::Value* _array) :
	CompilerHelper(_builder),
	m_array(_array),
	m_pushFunc([this](){ return createArrayPushFunc(); }),
	m_setFunc([this](){ return createArraySetFunc(); }),
	m_getFunc([this](){ return createArrayGetFunc(); }),
	m_freeFunc([this](){ return createFreeFunc(); })
{
	m_builder.CreateStore(llvm::ConstantAggregateZero::get(getType()), m_array);
}

void Array::pop(llvm::Value* _count)
{
	auto sizePtr = m_builder.CreateStructGEP(m_array, 1, "sizePtr");
	auto size = m_builder.CreateLoad(sizePtr, "size");
	auto newSize = m_builder.CreateNUWSub(size, _count, "newSize");
	m_builder.CreateStore(newSize, sizePtr);
}

llvm::Value* Array::size(llvm::Value* _array)
{
	auto sizePtr = m_builder.CreateStructGEP(_array ? _array : m_array, 1, "sizePtr");
	return m_builder.CreateLoad(sizePtr, "array.size");
}

void Array::extend(llvm::Value* _arrayPtr, llvm::Value* _size)
{
	assert(_arrayPtr->getType() == m_array->getType());
	assert(_size->getType() == Type::Size);
	m_extendFunc.call(m_builder, {_arrayPtr, _size});
}

}
}
}

extern "C"
{
	EXPORT void* ext_realloc(void* _data, size_t _size) noexcept
	{
		return std::realloc(_data, _size);
	}

	EXPORT void ext_free(void* _data) noexcept
	{
		std::free(_data);
	}
}
<|endoftext|>


<commit_before>#include "CommonData.hpp"
#include "IOLockWrapper.hpp"
#include "Config.hpp"
#include "Client.hpp"

namespace org_pqrs_KeyRemap4MacBook {
  AbsoluteTime CommonData::current_ts_;
  KeyboardType CommonData::current_keyboardType_;
  DeviceVendorID CommonData::current_deviceVendorID_;
  DeviceProductID CommonData::current_deviceProductID_;
  KeyRemap4MacBook_bridge::GetWorkspaceData::Reply CommonData::current_workspacedata_;
  IOLock* CommonData::eventLock = NULL;

  bool
  CommonData::initialize(void)
  {
    eventLock = IOLockWrapper::alloc();
    if (! eventLock) return false;

    return true;
  }

  void
  CommonData::terminate(void)
  {
    IOLockWrapper::free(eventLock);
  }

  void
  CommonData::setcurrent_workspacedata(void)
  {
    // ------------------------------------------------------------
    // When we press the functional key (ex. F2) with the keyboard of the third vendor,
    // KeyRemap4MacBook_client::sendmsg returns EIO.
    //
    // We use the previous value when the error occurred.
    static KeyRemap4MacBook_bridge::GetWorkspaceData::Reply last = {
      KeyRemap4MacBook_bridge::GetWorkspaceData::UNKNOWN,
      KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_ROMAN,
      KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_ROMAN,
    };

    int error = KeyRemap4MacBook_client::sendmsg(KeyRemap4MacBook_bridge::REQUEST_GET_WORKSPACE_DATA, NULL, 0, &current_workspacedata_, sizeof(current_workspacedata_));
    if (config.debug_devel) {
      printf("KeyRemap4MacBook -Info- GetWorkspaceData: %d,%d,%d (error: %d)\n",
             current_workspacedata_.type,
             current_workspacedata_.inputmode,
             current_workspacedata_.inputmodedetail,
             error);
    }
    if (error == 0) {
      last = current_workspacedata_;
    } else {
      // use last info.
      current_workspacedata_ = last;
    }
  }
}
<commit_msg>update CommonData to use IOLOG_*<commit_after>#include "CommonData.hpp"
#include "IOLockWrapper.hpp"
#include "Config.hpp"
#include "Client.hpp"

namespace org_pqrs_KeyRemap4MacBook {
  AbsoluteTime CommonData::current_ts_;
  KeyboardType CommonData::current_keyboardType_;
  DeviceVendorID CommonData::current_deviceVendorID_;
  DeviceProductID CommonData::current_deviceProductID_;
  KeyRemap4MacBook_bridge::GetWorkspaceData::Reply CommonData::current_workspacedata_;
  IOLock* CommonData::eventLock = NULL;

  bool
  CommonData::initialize(void)
  {
    eventLock = IOLockWrapper::alloc();
    if (! eventLock) return false;

    return true;
  }

  void
  CommonData::terminate(void)
  {
    IOLockWrapper::free(eventLock);
  }

  void
  CommonData::setcurrent_workspacedata(void)
  {
    // ------------------------------------------------------------
    // When we press the functional key (ex. F2) with the keyboard of the third vendor,
    // KeyRemap4MacBook_client::sendmsg returns EIO.
    //
    // We use the previous value when the error occurred.
    static KeyRemap4MacBook_bridge::GetWorkspaceData::Reply last = {
      KeyRemap4MacBook_bridge::GetWorkspaceData::UNKNOWN,
      KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_ROMAN,
      KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_ROMAN,
    };

    int error = KeyRemap4MacBook_client::sendmsg(KeyRemap4MacBook_bridge::REQUEST_GET_WORKSPACE_DATA, NULL, 0, &current_workspacedata_, sizeof(current_workspacedata_));
    IOLOG_DEVEL("GetWorkspaceData: type:%d, inputmode:%d, inputmodedetail:%d, error:%d\n",
                current_workspacedata_.type,
                current_workspacedata_.inputmode,
                current_workspacedata_.inputmodedetail,
                error);
    if (error == 0) {
      last = current_workspacedata_;
    } else {
      // use last info.
      current_workspacedata_ = last;
    }
  }
}
<|endoftext|>