<commit_before>//
// Copyright (C) 2013 Mateusz Łoskot <mateusz@loskot.net>
// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
//
#include "bbbuildconfiguration.hpp"
#include "bbbuildstep.hpp"
#include "bbproject.hpp"
#include "bbprojectfile.hpp"
#include "bbprojectmanager.hpp"
#include "bbprojectmanagerconstants.hpp"
#include "bbprojectnode.hpp"
#include "bbprojectreader.hpp"
#include "bbutility.hpp"
// Qt Creator
#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>
#include <coreplugin/generatedfile.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <cpptools/cppmodelmanagerinterface.h>
#include <cpptools/cpptoolsconstants.h>
#include <projectexplorer/kit.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectnodes.h>
#include <projectexplorer/target.h>
#include <qtsupport/customexecutablerunconfiguration.h>
#include <utils/QtConcurrentTools>
// Qt
#include <QDir>
#include <QFileInfo>
#include <QMessageBox>

namespace BoostBuildProjectManager {
namespace Internal {

// Project /////////////////////////////////////////////////////////////////////
Project::Project(ProjectManager* manager, QString const& fileName)
    : manager_(manager)
    , filePath_(fileName)
    , projectFile_(new ProjectFile(this, filePath_)) // enables projectDirectory()
    , projectNode_(new ProjectNode(this, projectFile_))
    , projectReader_(projectDirectory(projectFile_->filePath())) // avoid virtual call
{
    Q_ASSERT(manager_);
    Q_ASSERT(!filePath_.isEmpty());

    setProjectContext(Core::Context(Constants::PROJECT_CONTEXT));
    setProjectLanguages(Core::Context(ProjectExplorer::Constants::LANG_CXX));

    QFileInfo const projectFileInfo(filePath_);
    QDir const projectDir(projectFileInfo.dir());
    projectName_ = projectFileInfo.absoluteDir().dirName();
    filesFilePath_ = QFileInfo(projectDir, filePath_
        + QLatin1String(Constants::JAMFILE_FILES_EXT)).absoluteFilePath();
    includesFilePath_ = QFileInfo(projectDir, filePath_
        + QLatin1String(Constants::JAMFILE_INCLUDES_EXT)).absoluteFilePath();

    projectNode_->setDisplayName(projectName_);

    manager_->registerProject(this);

    // TODO
    //projectFileWatcher_->addPath(projectFilePath);
    //connect(projectFileWatcher_, SIGNAL(fileChanged(QString)), this, SLOT(refresh()));

    BBPM_QDEBUG("created project: "
                << displayName()
                << " (" << projectFileInfo.completeBaseName() << ")"
                << " in " << projectDirectory());
}

Project::~Project()
{
    manager_->unregisterProject(this);
    delete projectNode_;
}

QString Project::displayName() const
{
    return projectName_;
}

Core::Id Project::id() const
{
    return Core::Id(Constants::PROJECT_ID);
}

Core::IDocument* Project::document() const
{
    return projectFile_;
}

ProjectExplorer::IProjectManager* Project::projectManager() const
{
    return manager_;
}

ProjectExplorer::ProjectNode* Project::rootProjectNode() const
{
    return projectNode_;
}

QStringList Project::files(FilesMode fileMode) const
{
    Q_UNUSED(fileMode);
    BBPM_QDEBUG(displayName() << "has" << files_.size() << "files");
    //TODO: return projectReader_.files();
    return files_;
}

QStringList Project::files() const
{
    return files(FilesMode::AllFiles);
}

QString Project::filesFilePath() const
{
    Q_ASSERT(!filesFilePath_.isEmpty());
    return filesFilePath_;
}

QString Project::includesFilePath() const
{
    Q_ASSERT(!includesFilePath_.isEmpty());
    return includesFilePath_;
}

bool Project::needsConfiguration() const
{
    // TODO:
    // Does Boost.Build project require any configuration on loading?
    // - Kit selection
    // - build/stage directory
    // - targets listing
    // CMakeProjectManager seems to request configuration in fromMap()

    return false;
}

void Project::refresh()
{
    if (QFileInfo(filesFilePath()).exists())
    {
        QSet<QString> oldFileList;
        oldFileList = files_.toSet();

        // Parse project:
        // The manager does not parse Jamfile files.
        // Only generates and parses list of source files in Jamfile.${JAMFILE_FILES_EXT}
        QString const projectPath(projectDirectory());
        filesRaw_ = Utility::readLines(filesFilePath());
        files_ = Utility::makeAbsolutePaths(projectPath, filesRaw_);

        emit fileListChanged();

        projectNode_->refresh(oldFileList);

        using CppTools::CppModelManagerInterface;
        if (CppModelManagerInterface* cppManager = CppModelManagerInterface::instance())
        {
            CppModelManagerInterface::ProjectInfo cppInfo = cppManager->projectInfo(this);
            cppInfo.clearProjectParts();

            CppTools::ProjectPart::Ptr cppPart(new CppTools::ProjectPart());
            cppPart->project = this;
            cppPart->displayName = displayName();
            cppPart->projectFile = projectFilePath();
            cppPart->includePaths += projectDirectory();

            if (QFileInfo(includesFilePath_).exists())
            {
                cppPart->includePaths
                    += Utility::makeAbsolutePaths(projectPath
                    , Utility::readLines(includesFilePath()));
            }

            cppPart->cxxVersion = CppTools::ProjectPart::CXX11;
            // TODO: waiting for Jamfile parser
            //cppPart->defines +=

            ProjectExplorer::Kit const* k = activeTarget()
                ? activeTarget()->kit() : ProjectExplorer::KitManager::defaultKit();
            if (ProjectExplorer::ToolChain* tc
                    = ProjectExplorer::ToolChainKitInformation::toolChain(k))
            {
                // TODO: form GenericProjectmanager: FIXME: Can we do better?
                QStringList cxxflags;
                cppPart->evaluateToolchain(
                    tc, cxxflags, cxxflags
                  , ProjectExplorer::SysRootKitInformation::sysRoot(k));
            }
        }
    }
    else
    {
        // Read project tree on filesystem.

        connect(&projectReader_, SIGNAL(readingFinished())
              , this, SLOT(handleReadingFinished()));

        projectReader_.startReading();
    }
}

// This function is called at the very beginning to restore the settings
// from .user file, if there is any with previous settings stored.
bool Project::fromMap(QVariantMap const& map)
{
    BBPM_QDEBUG(displayName());

    if (!ProjectExplorer::Project::fromMap(map))
        return false;

    // TODO: Custom key/value from map

    // Set up active target and build configuration
    // NOTE: Call setActiveBuildConfiguration when creating new build configurations.
    if (!activeTarget())
    {
        // Configure project from scratch

        // TODO: do we need on-loading wizard similar to CMakeProjectManager?
        ProjectExplorer::Kit* defaultKit = ProjectExplorer::KitManager::defaultKit();
        ProjectExplorer::Target* target= createTarget(defaultKit);
        addTarget(target);
    }
    else
    {
        // Configure project from settings sorced from .user file
        BBPM_QDEBUG(displayName() << "has user file");
    }

    // Sanity check (taken from GenericProjectManager):
    // We need both a BuildConfiguration and a RunConfiguration!
    QList<ProjectExplorer::Target*> targetList = targets();
    foreach (ProjectExplorer::Target* t, targetList)
    {
        if (!t->activeBuildConfiguration())
        {
            removeTarget(t);
            continue;
        }
        if (!t->activeRunConfiguration())
            t->addRunConfiguration(
                        new QtSupport::CustomExecutableRunConfiguration(t));
    }

    QTC_ASSERT(hasActiveBuildSettings(), return false);
    QTC_ASSERT(activeTarget() != 0, return false);

    // Trigger loading project tree and parsing sources
    refresh();

    return true;
}

void Project::handleReadingFinished()
{
    QDir const projectDir(projectDirectory());
    QString errorMessage;

    // Generate .files file, all paths should be relative
    QStringList sources = projectReader_.files();
    Utility::makeRelativePaths(projectDir.absolutePath(), sources);

    Core::GeneratedFile gfFilesFile(filesFilePath());
    gfFilesFile.setContents(sources.join(QLatin1String("\n")));
    if (!gfFilesFile.write(&errorMessage))
    {
        QMessageBox::critical(0, tr("File Generation Failure"), errorMessage);
        return;
    }

    // Generate .includes file with all directories with headers
    QStringList const includePaths = projectReader_.includePaths();
    Core::GeneratedFile gfIncludesFile(includesFilePath());
    gfIncludesFile.setContents(includePaths.join(QLatin1String("\n")));
    if (!gfIncludesFile.write(&errorMessage))
    {
        QMessageBox::critical(0, tr("File Generation Failure"), errorMessage);
        return;
    }

    // Auxiliary files ready, complete refreshing project
    refresh();
}

// ProjectFilesFile ////////////////////////////////////////////////////////////
ProjectFilesFile::ProjectFilesFile(Project* parent, QString const& fileName)
    : Core::IDocument(parent)
    , project_(parent)
{
    setFilePath(fileName);
}

bool ProjectFilesFile::save(QString* errorString, QString const& fileName, bool autoSave)
{
    Q_UNUSED(errorString)
    Q_UNUSED(fileName)
    Q_UNUSED(autoSave)
    return false;
}

QString ProjectFilesFile::defaultPath() const
{
    return QString();
}

QString ProjectFilesFile::suggestedFileName() const
{
    return QString();
}

QString ProjectFilesFile::mimeType() const
{
    return QLatin1String(Constants::MIMETYPE_JAMFILE_FILES);
}

bool ProjectFilesFile::isModified() const
{
    return false;
}

bool ProjectFilesFile::isSaveAsAllowed() const
{
    return false;
}

Core::IDocument::ReloadBehavior
ProjectFilesFile::reloadBehavior(Core::IDocument::ChangeTrigger state
                               , Core::IDocument::ChangeType type) const
{
    Q_UNUSED(state)
    Q_UNUSED(type)
    return Core::IDocument::BehaviorSilent;
}

bool ProjectFilesFile::reload(QString* errorString, ReloadFlag flag, ChangeType type)
{
    Q_UNUSED(errorString)
    Q_UNUSED(flag)

    if (type == Core::IDocument::TypePermissions)
        return true;

    // TODO: reload list of files

    return true;
}

} // namespace Internal
} // namespace BoostBuildProjectManager
<commit_msg>Make use of include paths determined while reading project<commit_after>//
// Copyright (C) 2013 Mateusz Łoskot <mateusz@loskot.net>
// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
//
#include "bbbuildconfiguration.hpp"
#include "bbbuildstep.hpp"
#include "bbproject.hpp"
#include "bbprojectfile.hpp"
#include "bbprojectmanager.hpp"
#include "bbprojectmanagerconstants.hpp"
#include "bbprojectnode.hpp"
#include "bbprojectreader.hpp"
#include "bbutility.hpp"
// Qt Creator
#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>
#include <coreplugin/generatedfile.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <cpptools/cppmodelmanagerinterface.h>
#include <cpptools/cpptoolsconstants.h>
#include <projectexplorer/kit.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectnodes.h>
#include <projectexplorer/target.h>
#include <qtsupport/customexecutablerunconfiguration.h>
#include <utils/QtConcurrentTools>
// Qt
#include <QDir>
#include <QFileInfo>
#include <QMessageBox>

namespace BoostBuildProjectManager {
namespace Internal {

// Project /////////////////////////////////////////////////////////////////////
Project::Project(ProjectManager* manager, QString const& fileName)
    : manager_(manager)
    , filePath_(fileName)
    , projectFile_(new ProjectFile(this, filePath_)) // enables projectDirectory()
    , projectNode_(new ProjectNode(this, projectFile_))
    , projectReader_(projectDirectory(projectFile_->filePath())) // avoid virtual call
{
    Q_ASSERT(manager_);
    Q_ASSERT(!filePath_.isEmpty());

    setProjectContext(Core::Context(Constants::PROJECT_CONTEXT));
    setProjectLanguages(Core::Context(ProjectExplorer::Constants::LANG_CXX));

    QFileInfo const projectFileInfo(filePath_);
    QDir const projectDir(projectFileInfo.dir());
    projectName_ = projectFileInfo.absoluteDir().dirName();
    filesFilePath_ = QFileInfo(projectDir, filePath_
        + QLatin1String(Constants::JAMFILE_FILES_EXT)).absoluteFilePath();
    includesFilePath_ = QFileInfo(projectDir, filePath_
        + QLatin1String(Constants::JAMFILE_INCLUDES_EXT)).absoluteFilePath();

    projectNode_->setDisplayName(projectName_);

    manager_->registerProject(this);

    // TODO
    //projectFileWatcher_->addPath(projectFilePath);
    //connect(projectFileWatcher_, SIGNAL(fileChanged(QString)), this, SLOT(refresh()));

    BBPM_QDEBUG("created project: "
                << displayName()
                << " (" << projectFileInfo.completeBaseName() << ")"
                << " in " << projectDirectory());
}

Project::~Project()
{
    manager_->unregisterProject(this);
    delete projectNode_;
}

QString Project::displayName() const
{
    return projectName_;
}

Core::Id Project::id() const
{
    return Core::Id(Constants::PROJECT_ID);
}

Core::IDocument* Project::document() const
{
    return projectFile_;
}

ProjectExplorer::IProjectManager* Project::projectManager() const
{
    return manager_;
}

ProjectExplorer::ProjectNode* Project::rootProjectNode() const
{
    return projectNode_;
}

QStringList Project::files(FilesMode fileMode) const
{
    Q_UNUSED(fileMode);
    BBPM_QDEBUG(displayName() << "has" << files_.size() << "files");
    //TODO: return projectReader_.files();
    return files_;
}

QStringList Project::files() const
{
    return files(FilesMode::AllFiles);
}

QString Project::filesFilePath() const
{
    Q_ASSERT(!filesFilePath_.isEmpty());
    return filesFilePath_;
}

QString Project::includesFilePath() const
{
    Q_ASSERT(!includesFilePath_.isEmpty());
    return includesFilePath_;
}

bool Project::needsConfiguration() const
{
    // TODO:
    // Does Boost.Build project require any configuration on loading?
    // - Kit selection
    // - build/stage directory
    // - targets listing
    // CMakeProjectManager seems to request configuration in fromMap()

    return false;
}

void Project::refresh()
{
    if (QFileInfo(filesFilePath()).exists())
    {
        QSet<QString> oldFileList;
        oldFileList = files_.toSet();

        // Parse project:
        // The manager does not parse Jamfile files.
        // Only generates and parses list of source files in Jamfile.${JAMFILE_FILES_EXT}
        QString const projectPath(projectDirectory());
        filesRaw_ = Utility::readLines(filesFilePath());
        files_ = Utility::makeAbsolutePaths(projectPath, filesRaw_);

        QStringList includePaths =
            Utility::makeAbsolutePaths(projectPath,
                Utility::readLines(includesFilePath()));

        emit fileListChanged();

        projectNode_->refresh(oldFileList);

        using CppTools::CppModelManagerInterface;
        if (CppModelManagerInterface* cppManager = CppModelManagerInterface::instance())
        {
            CppModelManagerInterface::ProjectInfo cppInfo = cppManager->projectInfo(this);
            cppInfo.clearProjectParts();

            CppTools::ProjectPart::Ptr cppPart(new CppTools::ProjectPart());
            cppPart->project = this;
            cppPart->displayName = displayName();
            cppPart->projectFile = projectFilePath();
            cppPart->includePaths += projectDirectory();
            cppPart->includePaths += includePaths;

            cppPart->cxxVersion = CppTools::ProjectPart::CXX11;
            // TODO: waiting for Jamfile parser
            //cppPart->defines +=

            ProjectExplorer::Kit const* k = activeTarget()
                ? activeTarget()->kit() : ProjectExplorer::KitManager::defaultKit();
            if (ProjectExplorer::ToolChain* tc
                    = ProjectExplorer::ToolChainKitInformation::toolChain(k))
            {
                // TODO: form GenericProjectmanager: FIXME: Can we do better?
                QStringList cxxflags;
                cppPart->evaluateToolchain(
                    tc, cxxflags, cxxflags
                  , ProjectExplorer::SysRootKitInformation::sysRoot(k));
            }
        }
    }
    else
    {
        // Read project tree on filesystem.

        connect(&projectReader_, SIGNAL(readingFinished())
              , this, SLOT(handleReadingFinished()));

        projectReader_.startReading();
    }
}

// This function is called at the very beginning to restore the settings
// from .user file, if there is any with previous settings stored.
bool Project::fromMap(QVariantMap const& map)
{
    BBPM_QDEBUG(displayName());

    if (!ProjectExplorer::Project::fromMap(map))
        return false;

    // TODO: Custom key/value from map

    // Set up active target and build configuration
    // NOTE: Call setActiveBuildConfiguration when creating new build configurations.
    if (!activeTarget())
    {
        // Configure project from scratch

        // TODO: do we need on-loading wizard similar to CMakeProjectManager?
        ProjectExplorer::Kit* defaultKit = ProjectExplorer::KitManager::defaultKit();
        ProjectExplorer::Target* target= createTarget(defaultKit);
        addTarget(target);
    }
    else
    {
        // Configure project from settings sorced from .user file
        BBPM_QDEBUG(displayName() << "has user file");
    }

    // Sanity check (taken from GenericProjectManager):
    // We need both a BuildConfiguration and a RunConfiguration!
    QList<ProjectExplorer::Target*> targetList = targets();
    foreach (ProjectExplorer::Target* t, targetList)
    {
        if (!t->activeBuildConfiguration())
        {
            removeTarget(t);
            continue;
        }
        if (!t->activeRunConfiguration())
            t->addRunConfiguration(
                        new QtSupport::CustomExecutableRunConfiguration(t));
    }

    QTC_ASSERT(hasActiveBuildSettings(), return false);
    QTC_ASSERT(activeTarget() != 0, return false);

    // Trigger loading project tree and parsing sources
    refresh();

    return true;
}

void Project::handleReadingFinished()
{
    QDir const projectDir(projectDirectory());
    QString errorMessage;

    // Generate .files file, all paths should be relative
    QStringList sources = projectReader_.files();
    Utility::makeRelativePaths(projectDir.absolutePath(), sources);

    Core::GeneratedFile gfFilesFile(filesFilePath());
    gfFilesFile.setContents(sources.join(QLatin1String("\n")));
    if (!gfFilesFile.write(&errorMessage))
    {
        QMessageBox::critical(0, tr("File Generation Failure"), errorMessage);
        return;
    }

    // Generate .includes file with all directories with headers
    QStringList const includePaths = projectReader_.includePaths();
    Core::GeneratedFile gfIncludesFile(includesFilePath());
    gfIncludesFile.setContents(includePaths.join(QLatin1String("\n")));
    if (!gfIncludesFile.write(&errorMessage))
    {
        QMessageBox::critical(0, tr("File Generation Failure"), errorMessage);
        return;
    }

    // Auxiliary files ready, complete refreshing project
    refresh();
}

// ProjectFilesFile ////////////////////////////////////////////////////////////
ProjectFilesFile::ProjectFilesFile(Project* parent, QString const& fileName)
    : Core::IDocument(parent)
    , project_(parent)
{
    setFilePath(fileName);
}

bool ProjectFilesFile::save(QString* errorString, QString const& fileName, bool autoSave)
{
    Q_UNUSED(errorString)
    Q_UNUSED(fileName)
    Q_UNUSED(autoSave)
    return false;
}

QString ProjectFilesFile::defaultPath() const
{
    return QString();
}

QString ProjectFilesFile::suggestedFileName() const
{
    return QString();
}

QString ProjectFilesFile::mimeType() const
{
    return QLatin1String(Constants::MIMETYPE_JAMFILE_FILES);
}

bool ProjectFilesFile::isModified() const
{
    return false;
}

bool ProjectFilesFile::isSaveAsAllowed() const
{
    return false;
}

Core::IDocument::ReloadBehavior
ProjectFilesFile::reloadBehavior(Core::IDocument::ChangeTrigger state
                               , Core::IDocument::ChangeType type) const
{
    Q_UNUSED(state)
    Q_UNUSED(type)
    return Core::IDocument::BehaviorSilent;
}

bool ProjectFilesFile::reload(QString* errorString, ReloadFlag flag, ChangeType type)
{
    Q_UNUSED(errorString)
    Q_UNUSED(flag)

    if (type == Core::IDocument::TypePermissions)
        return true;

    // TODO: reload list of files

    return true;
}

} // namespace Internal
} // namespace BoostBuildProjectManager
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: plotareaconverter.hxx,v $
 *
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef OOX_DRAWINGML_CHART_PLOTAREACONVERTER_HXX
#define OOX_DRAWINGML_CHART_PLOTAREACONVERTER_HXX

#include "oox/drawingml/chart/converterbase.hxx"

namespace com { namespace sun { namespace star {
    namespace chart2 { class XDiagram; }
} } }

namespace oox {
namespace drawingml {
namespace chart {

// ============================================================================

struct View3DModel;
class TypeGroupConverter;

class View3DConverter : public ConverterBase< View3DModel >
{
public:
    explicit            View3DConverter( const ConverterRoot& rParent, View3DModel& rModel );
    virtual             ~View3DConverter();

    /** Converts the OOXML plot area model to a chart2 diagram. */
    void                convertFromModel(
                            const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram >& rxDiagram,
                            TypeGroupConverter& rTypeGroup );
};

// ============================================================================

struct PlotAreaModel;

class PlotAreaConverter : public ConverterBase< PlotAreaModel >
{
public:
    explicit            PlotAreaConverter( const ConverterRoot& rParent, PlotAreaModel& rModel );
    virtual             ~PlotAreaConverter();

    /** Converts the OOXML plot area model to a chart2 diagram.
        @return  Automatic chart title from a single series title, if possible. */
    ::rtl::OUString     convertFromModel( View3DModel& rView3DModel );
};

// ============================================================================

} // namespace chart
} // namespace drawingml
} // namespace oox

#endif

<commit_msg>INTEGRATION: CWS xmlfilter06 (1.2.6); FILE MERGED 2008/06/06 16:27:52 dr 1.2.6.2: chart formatting: builtin line/fill/effect styles, manual line formatting 2008/05/27 10:40:29 dr 1.2.6.1: joined changes from CWS xmlfilter05<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: plotareaconverter.hxx,v $
 *
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef OOX_DRAWINGML_CHART_PLOTAREACONVERTER_HXX
#define OOX_DRAWINGML_CHART_PLOTAREACONVERTER_HXX

#include "oox/drawingml/chart/converterbase.hxx"

namespace com { namespace sun { namespace star {
    namespace chart2 { class XDiagram; }
} } }

namespace oox {
namespace drawingml {
namespace chart {

// ============================================================================

struct View3DModel;
class TypeGroupConverter;

class View3DConverter : public ConverterBase< View3DModel >
{
public:
    explicit            View3DConverter( const ConverterRoot& rParent, View3DModel& rModel );
    virtual             ~View3DConverter();

    /** Converts the OOXML plot area model to a chart2 diagram. */
    void                convertFromModel(
                            const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram >& rxDiagram,
                            TypeGroupConverter& rTypeGroup );
};

// ============================================================================

struct WallFloorModel;

class WallFloorConverter : public ConverterBase< WallFloorModel >
{
public:
    explicit            WallFloorConverter( const ConverterRoot& rParent, WallFloorModel& rModel );
    virtual             ~WallFloorConverter();

    /** Converts the OOXML wall/floor model to a chart2 diagram. */
    void                convertFromModel(
                            const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram >& rxDiagram,
                            ObjectType eObjType );
};

// ============================================================================

struct PlotAreaModel;

class PlotAreaConverter : public ConverterBase< PlotAreaModel >
{
public:
    explicit            PlotAreaConverter( const ConverterRoot& rParent, PlotAreaModel& rModel );
    virtual             ~PlotAreaConverter();

    /** Converts the OOXML plot area model to a chart2 diagram. */
    void                convertFromModel( View3DModel& rView3DModel );

    /** Returns the automatic chart title if the chart contains only one series. */
    inline const ::rtl::OUString& getAutomaticTitle() const { return maAutoTitle; }
    /** Returns true, if the chart is three-dimensional. */
    inline bool         is3dChart() const { return mb3dChart; }
    /** Returns true, if chart type supports wall and floor format in 3D mode. */
    inline bool         isWall3dChart() const { return mbWall3dChart; }

private:
    ::rtl::OUString     maAutoTitle;
    bool                mb3dChart;
    bool                mbWall3dChart;
};

// ============================================================================

} // namespace chart
} // namespace drawingml
} // namespace oox

#endif

<|endoftext|>


<commit_before>/* +---------------------------------------------------------------------------+
   |                     Mobile Robot Programming Toolkit (MRPT)               |
   |                          http://www.mrpt.org/                             |
   |                                                                           |
   | Copyright (c) 2005-2016, Individual contributors, see AUTHORS file        |
   | See: http://www.mrpt.org/Authors - All rights reserved.                   |
   | Released under BSD License. See details in http://www.mrpt.org/License    |
   +---------------------------------------------------------------------------+ */

#include "hmtslam-precomp.h" // Precomp header

#include <mrpt/utils/CTicTac.h>
#include <mrpt/random.h>
#include <mrpt/utils/CFileStream.h>
#include <mrpt/system/os.h>

using namespace mrpt::slam;
using namespace mrpt::hmtslam;
using namespace mrpt::utils;

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

						CHMTSLAM_3D_viewer

	Optional 3D real-time viewer within HMT-SLAM

  ---------------------------------------------------------------*/
void CHMTSLAM::thread_3D_viewer(  )
{
	CHMTSLAM	*obj = this;
	CTicTac							tictac;

	try
	{
		// Start thread:
		// -------------------------
		obj->printf_debug("[thread_3D_viewer] Thread started (ID=0x%08lX)\n", mrpt::system::getCurrentThreadId() );

		// --------------------------------------------
		//    The main loop
		//  Executes until termination is signaled
		// --------------------------------------------
		while ( !obj->m_terminateThreads )
		{
			mrpt::system::sleep(100);
		};	// end while execute thread

		// Finish thread:
		// -------------------------
		time_t timCreat,timExit; double timCPU=0;
		try { mrpt::system::getCurrentThreadTimes( timCreat,timExit,timCPU); } catch(...) {};
		obj->printf_debug("[thread_3D_viewer] Thread finished. CPU time used:%.06f secs \n",timCPU);
		obj->m_terminationFlag_3D_viewer = true;

	}
	catch(std::exception &e)
	{
		obj->m_terminationFlag_3D_viewer = true;

		// Release semaphores:

		obj->printf_debug( (char*)e.what() );

		// DEBUG: Terminate application:
		obj->m_terminateThreads	= true;

	}
	catch(...)
	{
		obj->m_terminationFlag_3D_viewer = true;

		obj->printf_debug("\n---------------------- EXCEPTION CAUGHT! ---------------------\n");
		obj->printf_debug(" In CHierarchicalMappingFramework::thread_3D_viewer. Unexpected runtime error!!\n");

		// Release semaphores:

		// DEBUG: Terminate application:
		obj->m_terminateThreads	= true;
	}

}
<commit_msg>CHMTSLAM_3D_viewer Fix format string<commit_after>/* +---------------------------------------------------------------------------+
   |                     Mobile Robot Programming Toolkit (MRPT)               |
   |                          http://www.mrpt.org/                             |
   |                                                                           |
   | Copyright (c) 2005-2016, Individual contributors, see AUTHORS file        |
   | See: http://www.mrpt.org/Authors - All rights reserved.                   |
   | Released under BSD License. See details in http://www.mrpt.org/License    |
   +---------------------------------------------------------------------------+ */

#include "hmtslam-precomp.h" // Precomp header

#include <mrpt/utils/CTicTac.h>
#include <mrpt/random.h>
#include <mrpt/utils/CFileStream.h>
#include <mrpt/system/os.h>

using namespace mrpt::slam;
using namespace mrpt::hmtslam;
using namespace mrpt::utils;

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

						CHMTSLAM_3D_viewer

	Optional 3D real-time viewer within HMT-SLAM

  ---------------------------------------------------------------*/
void CHMTSLAM::thread_3D_viewer(  )
{
	CHMTSLAM	*obj = this;
	CTicTac							tictac;

	try
	{
		// Start thread:
		// -------------------------
		obj->printf_debug("[thread_3D_viewer] Thread started (ID=0x%08lX)\n", mrpt::system::getCurrentThreadId() );

		// --------------------------------------------
		//    The main loop
		//  Executes until termination is signaled
		// --------------------------------------------
		while ( !obj->m_terminateThreads )
		{
			mrpt::system::sleep(100);
		};	// end while execute thread

		// Finish thread:
		// -------------------------
		time_t timCreat,timExit; double timCPU=0;
		try { mrpt::system::getCurrentThreadTimes( timCreat,timExit,timCPU); } catch(...) {};
		obj->printf_debug("[thread_3D_viewer] Thread finished. CPU time used:%.06f secs \n",timCPU);
		obj->m_terminationFlag_3D_viewer = true;

	}
	catch(std::exception &e)
	{
		obj->m_terminationFlag_3D_viewer = true;

		// Release semaphores:

		obj->printf_debug("%s", e.what() );

		// DEBUG: Terminate application:
		obj->m_terminateThreads	= true;

	}
	catch(...)
	{
		obj->m_terminationFlag_3D_viewer = true;

		obj->printf_debug("\n---------------------- EXCEPTION CAUGHT! ---------------------\n");
		obj->printf_debug(" In CHierarchicalMappingFramework::thread_3D_viewer. Unexpected runtime error!!\n");

		// Release semaphores:

		// DEBUG: Terminate application:
		obj->m_terminateThreads	= true;
	}

}
<|endoftext|>


<commit_before>/*******************************************************************************
* CGoGN: Combinatorial and Geometric modeling with Generic N-dimensional Maps  *
* Copyright (C) 2015, IGG Group, ICube, University of Strasbourg, France       *
*                                                                              *
* 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.           *
*                                                                              *
* Web site: http://cgogn.unistra.fr/                                           *
* Contact information: cgogn@unistra.fr                                        *
*                                                                              *
*******************************************************************************/

#include <cgogn/core/basic/dart_marker.h>

namespace cgogn
{
} // namespace cgogn
<commit_msg>Delete empty dark_marker.cpp<commit_after><|endoftext|>


<commit_before>#include "queue.h"

namespace NP_ADT {
	template<class datatype>
	inline unsigned Queue<datatype>::getSize() const
	{
		return CDLL<datatype>::getSize();
	}

	template<class datatype>
	void Queue<datatype>::push(datatype & element)
	{
		push_back(element);
	}

	template<class datatype>
	datatype & Queue<datatype>::pop()
	{
		datatype popped_value = CDLL<datatype>::pop_front();
		datatype & popped_value_reference = popped_value;
		return popped_value_reference;
	}

}<commit_msg>fix pop()<commit_after>#include "queue.h"

namespace NP_ADT {
	template<class datatype>
	inline unsigned Queue<datatype>::getSize() const
	{
		return CDLL<datatype>::getSize();
	}

	template<class datatype>
	void Queue<datatype>::push(datatype & element)
	{
		push_back(element);
	}

	template<class datatype>
	datatype Queue<datatype>::pop()
	{
		return CDLL<datatype>::pop_front();
	}

}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: RangeHighlighter.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 18:21:13 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef CHART2_RANGEHIGHLIGHTER_HXX
#define CHART2_RANGEHIGHLIGHTER_HXX

#ifndef CHART_MUTEXCONTAINER_HXX
#include "MutexContainer.hxx"
#endif

#ifndef _CPPUHELPER_COMPBASE2_HXX_
#include <cppuhelper/compbase2.hxx>
#endif

#ifndef _COM_SUN_STAR_CHART2_DATA_XRANGEHIGHLIGHTER_HPP_
#include <com/sun/star/chart2/data/XRangeHighlighter.hpp>
#endif
#ifndef _COM_SUN_STAR_VIEW_XSELECTIONSUPPLIER_HPP_
#include <com/sun/star/view/XSelectionSupplier.hpp>
#endif

namespace com { namespace sun { namespace star {
namespace chart2 {
    class XDiagram;
    class XDataSeries;
    class XAxis;
}}}}

namespace chart
{

namespace impl
{
typedef ::cppu::WeakComponentImplHelper2<
        ::com::sun::star::chart2::data::XRangeHighlighter,
        ::com::sun::star::view::XSelectionChangeListener
    >
    RangeHighlighter_Base;
}

class RangeHighlighter :
        public MutexContainer,
        public impl::RangeHighlighter_Base
{
public:
    explicit RangeHighlighter(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::view::XSelectionSupplier > & xSelectionSupplier );
    virtual ~RangeHighlighter();

protected:
    // ____ XRangeHighlighter ____
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::chart2::data::HighlightedRange > SAL_CALL getSelectedRanges()
        throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addSelectionChangeListener(
        const ::com::sun::star::uno::Reference< ::com::sun::star::view::XSelectionChangeListener >& xListener )
        throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeSelectionChangeListener(
        const ::com::sun::star::uno::Reference< ::com::sun::star::view::XSelectionChangeListener >& xListener )
        throw (::com::sun::star::uno::RuntimeException);

    // ____ XSelectionChangeListener ____
    virtual void SAL_CALL selectionChanged(
        const ::com::sun::star::lang::EventObject& aEvent )
        throw (::com::sun::star::uno::RuntimeException);

    // ____ XEventListener (base of XSelectionChangeListener) ____
    virtual void SAL_CALL disposing(
        const ::com::sun::star::lang::EventObject& Source )
        throw (::com::sun::star::uno::RuntimeException);

    // ____ WeakComponentImplHelperBase ____
    // is called when dispose() is called at this component
    virtual void SAL_CALL disposing();

private:
    void fireSelectionEvent();
    void startListening();
    void stopListening();
    void determineRanges();

    void fillRangesForDiagram( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram > & xDiagram );
    void fillRangesForDataSeries( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries > & xSeries );
    void fillRangesForCategories( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XAxis > & xAxis );
    void fillRangesForDataPoint( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > & xDataSeries, sal_Int32 nIndex );

    ::com::sun::star::uno::Reference< ::com::sun::star::view::XSelectionSupplier >
        m_xSelectionSupplier;
    ::com::sun::star::uno::Reference< ::com::sun::star::view::XSelectionChangeListener >
        m_xListener;
    ::com::sun::star::uno::Sequence< ::com::sun::star::chart2::data::HighlightedRange >
        m_aSelectedRanges;
    sal_Int32 m_nAddedListenerCount;
};

} //  namespace chart

// CHART2_RANGEHIGHLIGHTER_HXX
#endif
<commit_msg>INTEGRATION: CWS chart20_DEV300 (1.2.108); FILE MERGED 2008/02/21 15:59:27 bm 1.2.108.1: #i366# error bars from ranges<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: RangeHighlighter.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-06 17:06:01 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef CHART2_RANGEHIGHLIGHTER_HXX
#define CHART2_RANGEHIGHLIGHTER_HXX

#ifndef CHART_MUTEXCONTAINER_HXX
#include "MutexContainer.hxx"
#endif

#ifndef _CPPUHELPER_COMPBASE2_HXX_
#include <cppuhelper/compbase2.hxx>
#endif

#ifndef _COM_SUN_STAR_CHART2_DATA_XRANGEHIGHLIGHTER_HPP_
#include <com/sun/star/chart2/data/XRangeHighlighter.hpp>
#endif
#ifndef _COM_SUN_STAR_VIEW_XSELECTIONSUPPLIER_HPP_
#include <com/sun/star/view/XSelectionSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

namespace com { namespace sun { namespace star {
namespace chart2 {
    class XDiagram;
    class XDataSeries;
    class XAxis;
}}}}

namespace chart
{

namespace impl
{
typedef ::cppu::WeakComponentImplHelper2<
        ::com::sun::star::chart2::data::XRangeHighlighter,
        ::com::sun::star::view::XSelectionChangeListener
    >
    RangeHighlighter_Base;
}

class RangeHighlighter :
        public MutexContainer,
        public impl::RangeHighlighter_Base
{
public:
    explicit RangeHighlighter(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::view::XSelectionSupplier > & xSelectionSupplier );
    virtual ~RangeHighlighter();

protected:
    // ____ XRangeHighlighter ____
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::chart2::data::HighlightedRange > SAL_CALL getSelectedRanges()
        throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addSelectionChangeListener(
        const ::com::sun::star::uno::Reference< ::com::sun::star::view::XSelectionChangeListener >& xListener )
        throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeSelectionChangeListener(
        const ::com::sun::star::uno::Reference< ::com::sun::star::view::XSelectionChangeListener >& xListener )
        throw (::com::sun::star::uno::RuntimeException);

    // ____ XSelectionChangeListener ____
    virtual void SAL_CALL selectionChanged(
        const ::com::sun::star::lang::EventObject& aEvent )
        throw (::com::sun::star::uno::RuntimeException);

    // ____ XEventListener (base of XSelectionChangeListener) ____
    virtual void SAL_CALL disposing(
        const ::com::sun::star::lang::EventObject& Source )
        throw (::com::sun::star::uno::RuntimeException);

    // ____ WeakComponentImplHelperBase ____
    // is called when dispose() is called at this component
    virtual void SAL_CALL disposing();

private:
    void fireSelectionEvent();
    void startListening();
    void stopListening();
    void determineRanges();

    void fillRangesForDiagram( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram > & xDiagram );
    void fillRangesForDataSeries( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries > & xSeries );
    void fillRangesForCategories( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XAxis > & xAxis );
    void fillRangesForDataPoint( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > & xDataSeries, sal_Int32 nIndex );
    void fillRangesForErrorBars( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & xErrorBar,
                                 const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries > & xDataSeries );

    ::com::sun::star::uno::Reference< ::com::sun::star::view::XSelectionSupplier >
        m_xSelectionSupplier;
    ::com::sun::star::uno::Reference< ::com::sun::star::view::XSelectionChangeListener >
        m_xListener;
    ::com::sun::star::uno::Sequence< ::com::sun::star::chart2::data::HighlightedRange >
        m_aSelectedRanges;
    sal_Int32 m_nAddedListenerCount;
};

} //  namespace chart

// CHART2_RANGEHIGHLIGHTER_HXX
#endif
<|endoftext|>


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

/* $Id$ */

//-------------------------------------------------------------------------
//     Event handler for ESD input reading the RecPoint Trees in parallel
//     Author: Andreas Morsch, CERN
//-------------------------------------------------------------------------

#include <TTree.h>
#include <TList.h>
#include <TFile.h>
#include <TArchiveFile.h>
#include <TSystemDirectory.h>
#include <TString.h>
#include <TObjString.h>
#include <TObjArray.h>
#include <TProcessID.h>
#include <TSystem.h>

#include "AliESDInputHandlerRP.h"
#include "AliESDEvent.h"
#include "AliESD.h"
#include "AliLog.h"

ClassImp(AliESDInputHandlerRP)

//______________________________________________________________________________
AliESDInputHandlerRP::AliESDInputHandlerRP() :
    AliESDInputHandler(),
    fRTrees(   new TObjArray()),
    fRDirs (   new TObjArray()),
    fRFiles(   new TList()),
    fDetectors(new TList()),
    fDirR(0),
    fEventNumber(-1),
    fFileNumber(0),
    fEventsPerFile(0),
    fExtension(""),
    fPathName(new TString("./")),
    fIsArchive(kFALSE)
{
  // Default constructor
}

//______________________________________________________________________________
AliESDInputHandlerRP::AliESDInputHandlerRP(const char* name, const char* title):
    AliESDInputHandler(name, title),
    fRTrees(   new TObjArray()),
    fRDirs (   new TObjArray()),
    fRFiles(   new TList()),
    fDetectors(new TList()),
    fDirR(0),
    fEventNumber(-1),
    fFileNumber(0),
    fEventsPerFile(0),
    fExtension(""),
    fPathName(new TString("./")),
    fIsArchive(kFALSE)
{
    // Constructor
}

//______________________________________________________________________________
AliESDInputHandlerRP::~AliESDInputHandlerRP()
{
  // Destructor
}

Bool_t AliESDInputHandlerRP::Init(Option_t* opt)
{
    //
    // Initialize input
    //
    if (!(strcmp(opt, "proof")) || !(strcmp(opt, "local"))) return kTRUE;
    //
    TIter next(fDetectors);
    TNamed* det;
    TFile* file = 0;
    while ((det = (TNamed*) next()))
    {
	if (!fIsArchive) {
	    file = TFile::Open(Form("%s%s.RecPoints.root", fPathName->Data(), det->GetName()));
	} else {
	    file = TFile::Open(Form("%s#%s.RecPoints.root", fPathName->Data(), det->GetName()));
	}
	if (!file) {
	  AliError(Form("AliESDInputHandlerRP: %s.RecPoints.root not found in %s ! \n", det->GetName(), fPathName->Data()));
	  return kFALSE;
	}
	fRFiles->Add(file);
    }

    if (file) {
	fEventsPerFile = file->GetNkeys() - file->GetNProcessIDs();
    } else {
	AliError(Form("AliESDInputHandlerRP: No file with RecPoints found in %s ! \n", fPathName->Data()));
	return kFALSE;
    }

    // Reset the event number
    fEventNumber      = -1;
    fFileNumber       =  0;
    // Get number of events from esd tree
    printf("AliESDInputHandlerRP::Init() %d %d\n",__LINE__, fNEvents);
    return kTRUE;
}

Bool_t AliESDInputHandlerRP::BeginEvent(Long64_t entry)
{
    // Begin the next event
    //
    if (entry == -1) {
	fEventNumber++;
	entry = fEventNumber;
    } else {
	fEventNumber = entry;
    }

    if (entry >= fNEvents) {
	AliWarning(Form("AliESDInputHandlerRP: Event number out of range %5lld %5d\n", entry, fNEvents));
	return kFALSE;
    }

    LoadEvent(entry);

    // Delegate to base class
    return AliESDInputHandler::BeginEvent(entry);

}

Bool_t AliESDInputHandlerRP::LoadEvent(Int_t iev)
{
    // Load the event number iev
    //
    // Calculate the file number
  if (fEventsPerFile<=0) return kFALSE;
    Int_t inew  = iev / fEventsPerFile;
    if (inew != fFileNumber) {
	fFileNumber = inew;
	if (!OpenFile(fFileNumber)){
	    return kFALSE;
	}
    }
    // Folder name
    char folder[20];
    sprintf(folder, "Event%d", iev);
    // Tree R
    TIter next(fRFiles);
    TFile* file;
    Int_t idx  = 0;

    while ((file = (TFile*) next()))
    {
	file->GetObject(folder, fDirR);

	if (!fDirR) {
	    AliWarning(Form("AliESDInputHandlerRP: Event #%5d not found\n", iev));
	    return kFALSE;
	}
	TTree* tree = 0;
	fDirR->GetObject("TreeR", tree);
	fRDirs ->AddAt(fDirR, idx  );
	fRTrees->AddAt(tree,  idx++);
    }
    return kTRUE;
}

Bool_t AliESDInputHandlerRP::OpenFile(Int_t i)
{
    // Open file i
    Bool_t ok = kTRUE;
    if (i > 0) {
	fExtension = Form("%d", i);
    } else {
	fExtension = "";
    }

    fRFiles->Delete();
    TIter next(fDetectors);
    TNamed* det;
    TFile* file;
    while ((det = (TNamed*) next()))
    {
	if (!fIsArchive) {
	    file = TFile::Open(Form("%s%s.RecPoints%s.root", fPathName->Data(), det->GetName(), fExtension));
	} else {
	    file = TFile::Open(Form("%s#%s.RecPoints%s.root", fPathName->Data(), det->GetName(), fExtension));
	}
	if (!file) AliFatal(Form("AliESDInputHandlerRP: RecPoints.root not found in %s ! \n", fPathName->Data()));
	fRFiles->Add(file);
    }
    return ok;
}

Bool_t AliESDInputHandlerRP::Notify(const char *path)
{
  // Notify about directory change
  // The directory is taken from the 'path' argument
  //
    AliInfo(Form("Directory change %s \n", path));
    // Get path to directory
    TString fileName(path);

    if(fileName.Contains("#")){
    // If this is an archive it will contain a #
      fIsArchive = kTRUE;
    } else  if(fileName.Contains("AliESDs.root")){
      fileName.ReplaceAll("AliESDs.root", "");
    }

    //
    // At this point we have a path to the directory or to the archive anchor
    *fPathName = fileName;
    //
    // Now filter the files containing RecPoints *.RecPoints.*

    TSeqCollection* members;

    if (fIsArchive) {
	// Archive
      TFile* file = TFile::Open(fPathName->Data());
      TArchiveFile* arch = file->GetArchive();
      members = arch->GetMembers();
      fPathName->ReplaceAll("#AliESDs.root", "");
    } else {
	// Directory or alien archive
      if (fileName.BeginsWith("alien:")) {
        TFile* file = TFile::Open(Form("%s/root_archive.zip", fPathName->Data()));
        TArchiveFile* arch = file->GetArchive();
        members = arch->GetMembers();
      } else {
        TString wd = gSystem->WorkingDirectory();
        TSystemDirectory dir(".", fPathName->Data());
        members = dir.GetListOfFiles();
        gSystem->cd(wd);
      }
    }

    TIter next(members);
    TFile* entry;
    Int_t ien = 0;
    fDetectors->Delete();

    while ( (entry = (TFile*) next()) )
    {
	TString name(entry->GetName());
	TObjArray* tokens = name.Tokenize(".");
	Int_t ntok = tokens->GetEntries();
	if (ntok <= 1) continue;
	TString str = ((TObjString*) tokens->At(1))->GetString();
	if (!(strcmp(str.Data(), "RecPoints"))){
	    TString det = ((TObjString*) tokens->At(0))->GetString();
	    printf("Found file with RecPoints for %s \n", det.Data());
	    TNamed* ent = new TNamed(det.Data(), det.Data());
	    fRTrees->AddAt(0, ien);
	    ent->SetUniqueID(ien++);
	    fDetectors->Add(ent);
	}
	if(tokens) delete tokens;
    } // loop over files

    // Now we have the path and the list of detectors

    printf("AliESDInputHandlerRP::Notify() Path: %s\n", fPathName->Data());
    //
    ResetIO();
    InitIO("");
    // Some clean-up
    if (members) members->Delete();

    AliESDInputHandler::Notify(path);

    return kTRUE;
}

Bool_t AliESDInputHandlerRP::FinishEvent()
{
    // Clean-up after each event
    fRDirs->Delete();
    AliESDInputHandler::FinishEvent();
    return kTRUE;
}

void AliESDInputHandlerRP::ResetIO()
{
// Delete trees and files
    fRFiles->Clear("nodelete");
    fExtension="";
}

TTree* AliESDInputHandlerRP::GetTreeR(const char* det)
{
// Return pointer to RecPoint tree for detector det
    TNamed* entry = (TNamed*) (fDetectors->FindObject(det));
    if (!entry) {
	AliWarning(Form("AliESDInputHandlerRP: No RecPoints for detector %s available \n", det));
	return 0;
    } else {
	Int_t ien = entry->GetUniqueID();
	return ((TTree*) (fRTrees->At(ien)));
    }
}
<commit_msg>Coverity bug corrected.<commit_after>/**************************************************************************
 * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

//-------------------------------------------------------------------------
//     Event handler for ESD input reading the RecPoint Trees in parallel
//     Author: Andreas Morsch, CERN
//-------------------------------------------------------------------------

#include <TTree.h>
#include <TList.h>
#include <TFile.h>
#include <TArchiveFile.h>
#include <TSystemDirectory.h>
#include <TString.h>
#include <TObjString.h>
#include <TObjArray.h>
#include <TProcessID.h>
#include <TSystem.h>

#include "AliESDInputHandlerRP.h"
#include "AliESDEvent.h"
#include "AliESD.h"
#include "AliLog.h"

ClassImp(AliESDInputHandlerRP)

//______________________________________________________________________________
AliESDInputHandlerRP::AliESDInputHandlerRP() :
    AliESDInputHandler(),
    fRTrees(   new TObjArray()),
    fRDirs (   new TObjArray()),
    fRFiles(   new TList()),
    fDetectors(new TList()),
    fDirR(0),
    fEventNumber(-1),
    fFileNumber(0),
    fEventsPerFile(0),
    fExtension(""),
    fPathName(new TString("./")),
    fIsArchive(kFALSE)
{
  // Default constructor
}

//______________________________________________________________________________
AliESDInputHandlerRP::AliESDInputHandlerRP(const char* name, const char* title):
    AliESDInputHandler(name, title),
    fRTrees(   new TObjArray()),
    fRDirs (   new TObjArray()),
    fRFiles(   new TList()),
    fDetectors(new TList()),
    fDirR(0),
    fEventNumber(-1),
    fFileNumber(0),
    fEventsPerFile(0),
    fExtension(""),
    fPathName(new TString("./")),
    fIsArchive(kFALSE)
{
    // Constructor
}

//______________________________________________________________________________
AliESDInputHandlerRP::~AliESDInputHandlerRP()
{
  // Destructor
}

Bool_t AliESDInputHandlerRP::Init(Option_t* opt)
{
    //
    // Initialize input
    //
    if (!(strcmp(opt, "proof")) || !(strcmp(opt, "local"))) return kTRUE;
    //
    TIter next(fDetectors);
    TNamed* det;
    TFile* file = 0;
    while ((det = (TNamed*) next()))
    {
	if (!fIsArchive) {
	    file = TFile::Open(Form("%s%s.RecPoints.root", fPathName->Data(), det->GetName()));
	} else {
	    file = TFile::Open(Form("%s#%s.RecPoints.root", fPathName->Data(), det->GetName()));
	}
	if (!file) {
	  AliError(Form("AliESDInputHandlerRP: %s.RecPoints.root not found in %s ! \n", det->GetName(), fPathName->Data()));
	  return kFALSE;
	}
	fRFiles->Add(file);
    }

    if (file) {
	fEventsPerFile = file->GetNkeys() - file->GetNProcessIDs();
    } else {
	AliError(Form("AliESDInputHandlerRP: No file with RecPoints found in %s ! \n", fPathName->Data()));
	return kFALSE;
    }

    // Reset the event number
    fEventNumber      = -1;
    fFileNumber       =  0;
    // Get number of events from esd tree
    printf("AliESDInputHandlerRP::Init() %d %d\n",__LINE__, fNEvents);
    return kTRUE;
}

Bool_t AliESDInputHandlerRP::BeginEvent(Long64_t entry)
{
    // Begin the next event
    //
    if (entry == -1) {
	fEventNumber++;
	entry = fEventNumber;
    } else {
	fEventNumber = entry;
    }

    if (entry >= fNEvents) {
	AliWarning(Form("AliESDInputHandlerRP: Event number out of range %5lld %5d\n", entry, fNEvents));
	return kFALSE;
    }

    LoadEvent(entry);

    // Delegate to base class
    return AliESDInputHandler::BeginEvent(entry);

}

Bool_t AliESDInputHandlerRP::LoadEvent(Int_t iev)
{
    // Load the event number iev
    //
    // Calculate the file number
  if (fEventsPerFile<=0) return kFALSE;
    Int_t inew  = iev / fEventsPerFile;
    if (inew != fFileNumber) {
	fFileNumber = inew;
	if (!OpenFile(fFileNumber)){
	    return kFALSE;
	}
    }
    // Folder name
    char folder[20];
    sprintf(folder, "Event%d", iev);
    // Tree R
    TIter next(fRFiles);
    TFile* file;
    Int_t idx  = 0;

    while ((file = (TFile*) next()))
    {
	file->GetObject(folder, fDirR);

	if (!fDirR) {
	    AliWarning(Form("AliESDInputHandlerRP: Event #%5d not found\n", iev));
	    return kFALSE;
	}
	TTree* tree = 0;
	fDirR->GetObject("TreeR", tree);
	fRDirs ->AddAt(fDirR, idx  );
	fRTrees->AddAt(tree,  idx++);
    }
    return kTRUE;
}

Bool_t AliESDInputHandlerRP::OpenFile(Int_t i)
{
    // Open file i
    Bool_t ok = kTRUE;
    if (i > 0) {
	fExtension = Form("%d", i);
    } else {
	fExtension = "";
    }

    fRFiles->Delete();
    TIter next(fDetectors);
    TNamed* det;
    TFile* file;
    while ((det = (TNamed*) next()))
    {
	if (!fIsArchive) {
	    file = TFile::Open(Form("%s%s.RecPoints%s.root", fPathName->Data(), det->GetName(), fExtension));
	} else {
	    file = TFile::Open(Form("%s#%s.RecPoints%s.root", fPathName->Data(), det->GetName(), fExtension));
	}
	if (!file) AliFatal(Form("AliESDInputHandlerRP: RecPoints.root not found in %s ! \n", fPathName->Data()));
	fRFiles->Add(file);
    }
    return ok;
}

Bool_t AliESDInputHandlerRP::Notify(const char *path)
{
  // Notify about directory change
  // The directory is taken from the 'path' argument
  //
    AliInfo(Form("Directory change %s \n", path));
    // Get path to directory
    TString fileName(path);

    if(fileName.Contains("#")){
    // If this is an archive it will contain a #
      fIsArchive = kTRUE;
    } else  if(fileName.Contains("AliESDs.root")){
      fileName.ReplaceAll("AliESDs.root", "");
    }

    //
    // At this point we have a path to the directory or to the archive anchor
    *fPathName = fileName;
    //
    // Now filter the files containing RecPoints *.RecPoints.*

    TSeqCollection* members;

    if (fIsArchive) {
	// Archive
      TFile* file = TFile::Open(fPathName->Data());
      TArchiveFile* arch = file->GetArchive();
      members = arch->GetMembers();
      fPathName->ReplaceAll("#AliESDs.root", "");
    } else {
	// Directory or alien archive
      if (fileName.BeginsWith("alien:")) {
        TFile* file = TFile::Open(Form("%s/root_archive.zip", fPathName->Data()));
        TArchiveFile* arch = file->GetArchive();
        members = arch->GetMembers();
      } else {
        TString wd = gSystem->WorkingDirectory();
        TSystemDirectory dir(".", fPathName->Data());
        members = dir.GetListOfFiles();
        gSystem->cd(wd);
      }
    }

    TIter next(members);
    TFile* entry;
    Int_t ien = 0;
    fDetectors->Delete();

    while ( (entry = (TFile*) next()) )
    {
	TString name(entry->GetName());
	TObjArray* tokens = name.Tokenize(".");
	Int_t ntok = 0;
	if (tokens) {
	  ntok = tokens->GetEntries();
	} else {
	  continue;
	}
	if (ntok <= 1) continue;
	TString str = ((TObjString*) tokens->At(1))->GetString();
	if (!(strcmp(str.Data(), "RecPoints"))){
	    TString det = ((TObjString*) tokens->At(0))->GetString();
	    printf("Found file with RecPoints for %s \n", det.Data());
	    TNamed* ent = new TNamed(det.Data(), det.Data());
	    fRTrees->AddAt(0, ien);
	    ent->SetUniqueID(ien++);
	    fDetectors->Add(ent);
	}
	if(tokens) delete tokens;
    } // loop over files

    // Now we have the path and the list of detectors

    printf("AliESDInputHandlerRP::Notify() Path: %s\n", fPathName->Data());
    //
    ResetIO();
    InitIO("");
    // Some clean-up
    if (members) members->Delete();

    AliESDInputHandler::Notify(path);

    return kTRUE;
}

Bool_t AliESDInputHandlerRP::FinishEvent()
{
    // Clean-up after each event
    fRDirs->Delete();
    AliESDInputHandler::FinishEvent();
    return kTRUE;
}

void AliESDInputHandlerRP::ResetIO()
{
// Delete trees and files
    fRFiles->Clear("nodelete");
    fExtension="";
}

TTree* AliESDInputHandlerRP::GetTreeR(const char* det)
{
// Return pointer to RecPoint tree for detector det
    TNamed* entry = (TNamed*) (fDetectors->FindObject(det));
    if (!entry) {
	AliWarning(Form("AliESDInputHandlerRP: No RecPoints for detector %s available \n", det));
	return 0;
    } else {
	Int_t ien = entry->GetUniqueID();
	return ((TTree*) (fRTrees->At(ien)));
    }
}
<|endoftext|>


<commit_before>#include "GeometryLoader.h"
#include "App.h"
#include "ModuleRenderer3D.h"
#include "Functions.h"
#include <gl/GL.h>
#include <gl/GLU.h>

#include "Assimp\include\cimport.h"
#include "Assimp\include\scene.h"
#include "Assimp\include\postprocess.h"
#include "Assimp\include\cfileio.h"

#pragma comment (lib, "Assimp/libx86/assimp.lib")

GeometryLoader::GeometryLoader(bool start_enabled) : Module(start_enabled)
{
}

GeometryLoader::~GeometryLoader()
{
}

bool GeometryLoader::Awake()
{
	bool ret = true;

	return ret;
}

bool GeometryLoader::Start()
{
	bool ret = true;

	// Stream log messages to Debug window
	struct aiLogStream stream;
	stream = aiGetPredefinedLogStream(aiDefaultLogStream_DEBUGGER, nullptr);
	aiAttachLogStream(&stream);

	LoadFile("BakerHouse.FBX");

	return ret;
}

bool GeometryLoader::Update()
{
	bool ret = true;

	for(vector<Mesh>::iterator it = meshes.begin(); it != meshes.end(); it++)
	{
		(*it).Draw();
	}

	return ret;
}

bool GeometryLoader::CleanUp()
{
	bool ret = true;

	// detach log stream
	aiDetachAllLogStreams();

	return ret;
}

void GeometryLoader::OnLoadFile(const char* file_path, const char* file_extension)
{
	if (TextCmp("fbx", file_extension))
	{
		UnloadAllFiles();
		LoadFile(file_path);
	}
}

bool GeometryLoader::LoadFile(const char * full_path)
{
	bool ret = false;

	const aiScene* scene = aiImportFile(full_path, aiProcessPreset_TargetRealtime_MaxQuality);
	if (scene != nullptr && scene->HasMeshes())
	{
		LOG_OUTPUT("LOADING %d MESHES", scene->mNumMeshes);

		// Use scene->mNumMeshes to iterate on scene->mMeshes array
		for (int i = 0; i < scene->mNumMeshes; ++i)
		{
			Mesh new_mesh;

			// copy vertices
			aiMesh* current_mesh = scene->mMeshes[i];

			new_mesh.num_vertices = current_mesh->mNumVertices;
			new_mesh.vertices = new float[new_mesh.num_vertices * 3];
			memcpy(new_mesh.vertices, current_mesh->mVertices, sizeof(float) * new_mesh.num_vertices * 3);

			LOG_OUTPUT("New mesh with %d vertices", new_mesh.num_vertices);

			// copy faces
			if (current_mesh->HasFaces())
			{
				new_mesh.num_indices = current_mesh->mNumFaces * 3;
				new_mesh.indices = new uint[new_mesh.num_indices]; // assume each face is a triangle

				for (uint i = 0; i < current_mesh->mNumFaces; ++i)
				{
					if (current_mesh->mFaces[i].mNumIndices != 3)
					{
						LOG_OUTPUT("WARNING, geometry face with != 3 indices!");
						assert(current_mesh->mFaces[i].mNumIndices != 3, "WARNING, geometry face with != 3 indices!");
					}
					else
						memcpy(&new_mesh.indices[i * 3], current_mesh->mFaces[i].mIndices, 3 * sizeof(uint));
				}
			}
			LOG_OUTPUT("New mesh with %d indices", new_mesh.num_indices);

			// Add mesh to vector<Mesh> meshes
			new_mesh.LoadToMemory();

			meshes.push_back(new_mesh);
		}

		aiReleaseImport(scene);
		ret = true;
	}
	else
		LOG_OUTPUT("Error loading scene %s", full_path);

	return ret;
}

void GeometryLoader::UnloadFile(Mesh mesh)
{
	for (vector<Mesh>::iterator it = meshes.begin(); it != meshes.end(); it++)
	{
		if ((*it) == mesh)
		{
			(*it).UnloadFromMemory();
			meshes.erase(it);
			break;
		}
	}
}

void GeometryLoader::UnloadAllFiles()
{
	for (vector<Mesh>::iterator it = meshes.begin(); it != meshes.end();)
	{
		(*it).UnloadFromMemory();
		it = meshes.erase(it);

	}
}

Mesh::Mesh(uint _id_vertices, uint _num_indices, uint * _indices, uint _id_indices, uint _num_vertices, float * _vertices)
{
	id_vertices = _id_vertices;
	num_indices = _num_indices;
	indices = _indices;
	id_indices = _id_indices;
	num_vertices = _num_vertices;
	vertices = _vertices;
}

void Mesh::LoadToMemory()
{
	if(id_vertices == 0)
		id_vertices = App->renderer3D->LoadBuffer(vertices, num_vertices*3);

	if(id_indices == 0)
		id_indices = App->renderer3D->LoadBuffer(indices, num_indices);
}

void Mesh::UnloadFromMemory()
{
	if (id_vertices != 0)
	{
		App->renderer3D->UnloadBuffer(id_vertices, num_vertices * 3);
		id_vertices = 0;
	}

	if (id_indices != 0)
	{
		App->renderer3D->UnloadBuffer(id_indices, num_indices);
		id_indices = 0;
	}
}

void Mesh::Draw()
{
	if (id_indices != 0 && id_vertices != 0)
		App->renderer3D->DrawIndexBuffer(GL_TRIANGLES, id_indices, num_indices, id_vertices);
}
<commit_msg>Code left from last commit<commit_after>#include "GeometryLoader.h"
#include "App.h"
#include "ModuleRenderer3D.h"
#include "Functions.h"
#include <gl/GL.h>
#include <gl/GLU.h>

#include "Assimp\include\cimport.h"
#include "Assimp\include\scene.h"
#include "Assimp\include\postprocess.h"
#include "Assimp\include\cfileio.h"

#pragma comment (lib, "Assimp/libx86/assimp.lib")

GeometryLoader::GeometryLoader(bool start_enabled) : Module(start_enabled)
{
}

GeometryLoader::~GeometryLoader()
{
}

bool GeometryLoader::Awake()
{
	bool ret = true;

	return ret;
}

bool GeometryLoader::Start()
{
	bool ret = true;

	// Stream log messages to Debug window
	struct aiLogStream stream;
	stream = aiGetPredefinedLogStream(aiDefaultLogStream_DEBUGGER, nullptr);
	aiAttachLogStream(&stream);

	LoadFile("BakerHouse.FBX");

	return ret;
}

bool GeometryLoader::Update()
{
	bool ret = true;

	for(vector<Mesh>::iterator it = meshes.begin(); it != meshes.end(); it++)
	{
		(*it).Draw();
	}

	return ret;
}

bool GeometryLoader::CleanUp()
{
	bool ret = true;

	UnloadAllFiles();

	// detach log stream
	aiDetachAllLogStreams();

	return ret;
}

void GeometryLoader::OnLoadFile(const char* file_path, const char* file_extension)
{
	if (TextCmp("fbx", file_extension))
	{
		UnloadAllFiles();
		LoadFile(file_path);
	}
}

bool GeometryLoader::LoadFile(const char * full_path)
{
	bool ret = false;

	const aiScene* scene = aiImportFile(full_path, aiProcessPreset_TargetRealtime_MaxQuality);
	if (scene != nullptr && scene->HasMeshes())
	{
		LOG_OUTPUT("LOADING %d MESHES", scene->mNumMeshes);

		// Use scene->mNumMeshes to iterate on scene->mMeshes array
		for (int i = 0; i < scene->mNumMeshes; ++i)
		{
			Mesh new_mesh;

			// copy vertices
			aiMesh* current_mesh = scene->mMeshes[i];

			new_mesh.num_vertices = current_mesh->mNumVertices;
			new_mesh.vertices = new float[new_mesh.num_vertices * 3];
			memcpy(new_mesh.vertices, current_mesh->mVertices, sizeof(float) * new_mesh.num_vertices * 3);

			LOG_OUTPUT("New mesh with %d vertices", new_mesh.num_vertices);

			// copy faces
			if (current_mesh->HasFaces())
			{
				new_mesh.num_indices = current_mesh->mNumFaces * 3;
				new_mesh.indices = new uint[new_mesh.num_indices]; // assume each face is a triangle

				for (uint i = 0; i < current_mesh->mNumFaces; ++i)
				{
					if (current_mesh->mFaces[i].mNumIndices != 3)
					{
						LOG_OUTPUT("WARNING, geometry face with != 3 indices!");
						assert(current_mesh->mFaces[i].mNumIndices != 3, "WARNING, geometry face with != 3 indices!");
					}
					else
						memcpy(&new_mesh.indices[i * 3], current_mesh->mFaces[i].mIndices, 3 * sizeof(uint));
				}
			}
			LOG_OUTPUT("New mesh with %d indices", new_mesh.num_indices);

			// Add mesh to vector<Mesh> meshes
			new_mesh.LoadToMemory();

			meshes.push_back(new_mesh);
		}

		aiReleaseImport(scene);
		ret = true;
	}
	else
		LOG_OUTPUT("Error loading scene %s", full_path);

	return ret;
}

void GeometryLoader::UnloadFile(Mesh mesh)
{
	for (vector<Mesh>::iterator it = meshes.begin(); it != meshes.end(); it++)
	{
		if ((*it) == mesh)
		{
			(*it).UnloadFromMemory();
			meshes.erase(it);
			break;
		}
	}
}

void GeometryLoader::UnloadAllFiles()
{
	for (vector<Mesh>::iterator it = meshes.begin(); it != meshes.end();)
	{
		(*it).UnloadFromMemory();
		it = meshes.erase(it);

	}
}

Mesh::Mesh(uint _id_vertices, uint _num_indices, uint * _indices, uint _id_indices, uint _num_vertices, float * _vertices)
{
	id_vertices = _id_vertices;
	num_indices = _num_indices;
	indices = _indices;
	id_indices = _id_indices;
	num_vertices = _num_vertices;
	vertices = _vertices;
}

void Mesh::LoadToMemory()
{
	if(id_vertices == 0)
		id_vertices = App->renderer3D->LoadBuffer(vertices, num_vertices*3);

	if(id_indices == 0)
		id_indices = App->renderer3D->LoadBuffer(indices, num_indices);
}

void Mesh::UnloadFromMemory()
{
	if (id_vertices != 0)
	{
		App->renderer3D->UnloadBuffer(id_vertices, num_vertices * 3);
		id_vertices = 0;
	}

	if (id_indices != 0)
	{
		App->renderer3D->UnloadBuffer(id_indices, num_indices);
		id_indices = 0;
	}
}

void Mesh::Draw()
{
	if (id_indices != 0 && id_vertices != 0)
		App->renderer3D->DrawIndexBuffer(GL_TRIANGLES, id_indices, num_indices, id_vertices);
}
<|endoftext|>