<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: KStatement.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2006-07-06 14:21:35 $
 *
 *  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 _CONNECTIVITY_KAB_STATEMENT_HXX_
#define _CONNECTIVITY_KAB_STATEMENT_HXX_

#ifndef _CONNECTIVITY_KAB_CONNECTION_HXX_
#include "KConnection.hxx"
#endif
#include <list>

#ifndef _CONNECTIVITY_PARSE_SQLITERATOR_HXX_
#include "connectivity/sqliterator.hxx"
#endif
#ifndef _CONNECTIVITY_PARSE_SQLPARSE_HXX_
#include "connectivity/sqlparse.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XSTATEMENT_HPP_
#include <com/sun/star/sdbc/XStatement.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XCANCELLABLE_HPP_
#include <com/sun/star/util/XCancellable.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE4_HXX_
#include <cppuhelper/compbase4.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif

namespace connectivity
{
    namespace kab
    {
        typedef ::cppu::WeakComponentImplHelper4<   ::com::sun::star::sdbc::XStatement,
                                                    ::com::sun::star::sdbc::XWarningsSupplier,
                                                    ::com::sun::star::util::XCancellable,
                                                    ::com::sun::star::sdbc::XCloseable> KabCommonStatement_BASE;

        //**************************************************************
        // Class KabCommonStatement
        // is a base class for the normal statement and for the prepared statement
        //**************************************************************
        class KabCommonStatement :  public comphelper::OBaseMutex,
                        public  KabCommonStatement_BASE,
                        public  ::cppu::OPropertySetHelper,
                        public  comphelper::OPropertyArrayUsageHelper<KabCommonStatement>

        {
            ::com::sun::star::sdbc::SQLWarning  m_aLastWarning;

        protected:
            ::std::list< ::rtl::OUString>       m_aBatchList;
            connectivity::OSQLParser            m_aParser;
            connectivity::OSQLParseTreeIterator m_aSQLIterator;
            connectivity::OSQLParseNode*        m_pParseTree;
            KabConnection*                      m_pConnection;  // The owning Connection object

        protected:
            class KabCondition *analyseWhereClause(
                const OSQLParseNode *pParseNode) const throw(::com::sun::star::sdbc::SQLException);
            class KabOrder *analyseOrderByClause(
                const OSQLParseNode *pParseNode) const throw(::com::sun::star::sdbc::SQLException);
            sal_Bool isTableKnown(class KabResultSet *pResult) const;
            void setKabFields(class KabResultSet *pResult) const throw(::com::sun::star::sdbc::SQLException);
            void selectAddressees(KabResultSet *pResult) const throw(::com::sun::star::sdbc::SQLException);
            void sortAddressees(KabResultSet *pResult) const throw(::com::sun::star::sdbc::SQLException);

            // OPropertyArrayUsageHelper
            virtual ::cppu::IPropertyArrayHelper* createArrayHelper() const;

            // OPropertySetHelper
            virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();
            virtual sal_Bool SAL_CALL convertFastPropertyValue(
                    ::com::sun::star::uno::Any & rConvertedValue,
                    ::com::sun::star::uno::Any & rOldValue,
                    sal_Int32 nHandle,
                    const ::com::sun::star::uno::Any& rValue) throw (::com::sun::star::lang::IllegalArgumentException);
            virtual void SAL_CALL setFastPropertyValue_NoBroadcast(
                    sal_Int32 nHandle,
                    const ::com::sun::star::uno::Any& rValue) throw (::com::sun::star::uno::Exception);
            virtual void SAL_CALL getFastPropertyValue(
                    ::com::sun::star::uno::Any& rValue,
                    sal_Int32 nHandle) const;

            virtual void resetParameters() const throw(::com::sun::star::sdbc::SQLException);
            virtual void getNextParameter(::rtl::OUString &rParameter) const throw(::com::sun::star::sdbc::SQLException);
            virtual ~KabCommonStatement();

        public:
            ::cppu::OBroadcastHelper& rBHelper;

            KabCommonStatement(KabConnection *_pConnection);
            using KabCommonStatement_BASE::operator ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >;

            // OComponentHelper
            virtual void SAL_CALL disposing();

            // XInterface
            virtual void SAL_CALL release() throw();
            virtual void SAL_CALL acquire() throw();
            virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(
                    const ::com::sun::star::uno::Type & rType
                    ) throw(::com::sun::star::uno::RuntimeException);

            // XTypeProvider
            virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(
                    ) throw(::com::sun::star::uno::RuntimeException);

            // XPropertySet
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(
                    ) throw(::com::sun::star::uno::RuntimeException);

            // XStatement
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL executeQuery(
                    const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL executeUpdate(
                     const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL execute(
                    const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection(
                    ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

            // XWarningsSupplier
            virtual ::com::sun::star::uno::Any SAL_CALL getWarnings(
                    ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL clearWarnings(
                    ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

            // XCancellable
            virtual void SAL_CALL cancel(
                    ) throw(::com::sun::star::uno::RuntimeException);

            // XCloseable
            virtual void SAL_CALL close(
                    ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

            // other methods
            inline KabConnection* getOwnConnection() const { return m_pConnection; }
        };

        //**************************************************************
        // Class KabStatement
        //**************************************************************
        typedef ::cppu::ImplInheritanceHelper1<
                KabCommonStatement, ::com::sun::star::lang::XServiceInfo > KabStatement_BASE;

        class KabStatement : public KabStatement_BASE
        {
        protected:
            virtual ~KabStatement() { }

        public:
            KabStatement(KabConnection* _pConnection);
            DECLARE_SERVICE_INFO();
        };
    }
}

#endif // _CONNECTIVITY_KAB_STATEMENT_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.3.266); FILE MERGED 2008/04/01 15:08:53 thb 1.3.266.3: #i85898# Stripping all external header guards 2008/04/01 10:53:07 thb 1.3.266.2: #i85898# Stripping all external header guards 2008/03/28 15:23:45 rt 1.3.266.1: #i87441# Change license header to LPGL v3.<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: KStatement.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 _CONNECTIVITY_KAB_STATEMENT_HXX_
#define _CONNECTIVITY_KAB_STATEMENT_HXX_

#include "KConnection.hxx"
#include <list>
#include "connectivity/sqliterator.hxx"
#ifndef _CONNECTIVITY_PARSE_SQLPARSE_HXX_
#include "connectivity/sqlparse.hxx"
#endif
#include <com/sun/star/sdbc/XStatement.hpp>
#include <com/sun/star/util/XCancellable.hpp>
#include <cppuhelper/compbase4.hxx>
#include <cppuhelper/implbase1.hxx>
#include <comphelper/proparrhlp.hxx>

namespace connectivity
{
    namespace kab
    {
        typedef ::cppu::WeakComponentImplHelper4<   ::com::sun::star::sdbc::XStatement,
                                                    ::com::sun::star::sdbc::XWarningsSupplier,
                                                    ::com::sun::star::util::XCancellable,
                                                    ::com::sun::star::sdbc::XCloseable> KabCommonStatement_BASE;

        //**************************************************************
        // Class KabCommonStatement
        // is a base class for the normal statement and for the prepared statement
        //**************************************************************
        class KabCommonStatement :  public comphelper::OBaseMutex,
                        public  KabCommonStatement_BASE,
                        public  ::cppu::OPropertySetHelper,
                        public  comphelper::OPropertyArrayUsageHelper<KabCommonStatement>

        {
            ::com::sun::star::sdbc::SQLWarning  m_aLastWarning;

        protected:
            ::std::list< ::rtl::OUString>       m_aBatchList;
            connectivity::OSQLParser            m_aParser;
            connectivity::OSQLParseTreeIterator m_aSQLIterator;
            connectivity::OSQLParseNode*        m_pParseTree;
            KabConnection*                      m_pConnection;  // The owning Connection object

        protected:
            class KabCondition *analyseWhereClause(
                const OSQLParseNode *pParseNode) const throw(::com::sun::star::sdbc::SQLException);
            class KabOrder *analyseOrderByClause(
                const OSQLParseNode *pParseNode) const throw(::com::sun::star::sdbc::SQLException);
            sal_Bool isTableKnown(class KabResultSet *pResult) const;
            void setKabFields(class KabResultSet *pResult) const throw(::com::sun::star::sdbc::SQLException);
            void selectAddressees(KabResultSet *pResult) const throw(::com::sun::star::sdbc::SQLException);
            void sortAddressees(KabResultSet *pResult) const throw(::com::sun::star::sdbc::SQLException);

            // OPropertyArrayUsageHelper
            virtual ::cppu::IPropertyArrayHelper* createArrayHelper() const;

            // OPropertySetHelper
            virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();
            virtual sal_Bool SAL_CALL convertFastPropertyValue(
                    ::com::sun::star::uno::Any & rConvertedValue,
                    ::com::sun::star::uno::Any & rOldValue,
                    sal_Int32 nHandle,
                    const ::com::sun::star::uno::Any& rValue) throw (::com::sun::star::lang::IllegalArgumentException);
            virtual void SAL_CALL setFastPropertyValue_NoBroadcast(
                    sal_Int32 nHandle,
                    const ::com::sun::star::uno::Any& rValue) throw (::com::sun::star::uno::Exception);
            virtual void SAL_CALL getFastPropertyValue(
                    ::com::sun::star::uno::Any& rValue,
                    sal_Int32 nHandle) const;

            virtual void resetParameters() const throw(::com::sun::star::sdbc::SQLException);
            virtual void getNextParameter(::rtl::OUString &rParameter) const throw(::com::sun::star::sdbc::SQLException);
            virtual ~KabCommonStatement();

        public:
            ::cppu::OBroadcastHelper& rBHelper;

            KabCommonStatement(KabConnection *_pConnection);
            using KabCommonStatement_BASE::operator ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >;

            // OComponentHelper
            virtual void SAL_CALL disposing();

            // XInterface
            virtual void SAL_CALL release() throw();
            virtual void SAL_CALL acquire() throw();
            virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(
                    const ::com::sun::star::uno::Type & rType
                    ) throw(::com::sun::star::uno::RuntimeException);

            // XTypeProvider
            virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(
                    ) throw(::com::sun::star::uno::RuntimeException);

            // XPropertySet
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(
                    ) throw(::com::sun::star::uno::RuntimeException);

            // XStatement
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL executeQuery(
                    const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL executeUpdate(
                     const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL execute(
                    const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection(
                    ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

            // XWarningsSupplier
            virtual ::com::sun::star::uno::Any SAL_CALL getWarnings(
                    ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL clearWarnings(
                    ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

            // XCancellable
            virtual void SAL_CALL cancel(
                    ) throw(::com::sun::star::uno::RuntimeException);

            // XCloseable
            virtual void SAL_CALL close(
                    ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

            // other methods
            inline KabConnection* getOwnConnection() const { return m_pConnection; }
        };

        //**************************************************************
        // Class KabStatement
        //**************************************************************
        typedef ::cppu::ImplInheritanceHelper1<
                KabCommonStatement, ::com::sun::star::lang::XServiceInfo > KabStatement_BASE;

        class KabStatement : public KabStatement_BASE
        {
        protected:
            virtual ~KabStatement() { }

        public:
            KabStatement(KabConnection* _pConnection);
            DECLARE_SERVICE_INFO();
        };
    }
}

#endif // _CONNECTIVITY_KAB_STATEMENT_HXX_
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <chrono>
#include <cstdlib>

#define VIENNACL_WITH_OPENCL
#define AGGREGATION
#define AMGCL_PROFILING

#include <amgcl/amgcl.hpp>

#ifdef AGGREGATION
#  include <amgcl/aggregation.hpp>
#else
#  include <amgcl/interp_classic.hpp>
#endif

#include <amgcl/level_viennacl.hpp>

#include <vexcl/devlist.hpp>

#include <viennacl/vector.hpp>
#include <viennacl/hyb_matrix.hpp>
#include <viennacl/linalg/cg.hpp>

namespace amgcl {
profiler<> prof;
}
using amgcl::prof;

// Simple wrapper around amgcl::solver that provides ViennaCL's preconditioner
// interface.
struct amg_precond {
    typedef amgcl::solver<
        double, int,
#ifdef AGGREGATION
        amgcl::interp::aggregation<amgcl::aggr::plain>,
#else
        amgcl::interp::classic,
#endif
        amgcl::level::ViennaCL<amgcl::level::CL_MATRIX_HYB>
        > AMG;
    typedef typename AMG::params params;

    // Build AMG hierarchy.
    template <class matrix>
    amg_precond(const matrix &A, const params &prm = params())
        : amg(A, prm), r(amgcl::sparse::matrix_rows(A))
    { }

    // Use one V-cycle with zero initial approximation as a preconditioning step.
    void apply(viennacl::vector<double> &x) const {
        r.clear();
        amg.apply(x, r);
        viennacl::copy(r, x);
    }

    // Build VexCL-based hierarchy:
    mutable AMG amg;
    mutable viennacl::vector<double> r;
};

int main(int argc, char *argv[]) {
    if (argc < 2) {
        std::cerr << "Usage: " << argv[0] << " <problem.dat>" << std::endl;
        return 1;
    }

    // There is no easy way to select compute device in ViennaCL, so just use
    // VexCL for that.
    vex::Context ctx(
            vex::Filter::Env &&
            vex::Filter::DoublePrecision &&
            vex::Filter::Count(1)
            );
    std::vector<cl_device_id> dev_id(1, ctx.queue(0).getInfo<CL_QUEUE_DEVICE>()());
    std::vector<cl_command_queue> queue_id(1, ctx.queue(0)());
    viennacl::ocl::setup_context(0, ctx.context(0)(), dev_id, queue_id);
    std::cout << ctx << std::endl;

    // Read matrix and rhs from a binary file.
    std::ifstream pfile(argv[1], std::ios::binary);
    int n;
    pfile.read((char*)&n, sizeof(int));

    std::vector<int> row(n + 1);
    pfile.read((char*)row.data(), row.size() * sizeof(int));

    std::vector<int>    col(row.back());
    std::vector<double> val(row.back());
    std::vector<double> rhs(n);

    pfile.read((char*)col.data(), col.size() * sizeof(int));
    pfile.read((char*)val.data(), val.size() * sizeof(double));
    pfile.read((char*)rhs.data(), rhs.size() * sizeof(double));

    // Wrap the matrix into amgcl::sparse::map:
    amgcl::sparse::matrix_map<double, int> A(
            n, n, row.data(), col.data(), val.data()
            );

    // Build the preconditioner.
    amg_precond::params prm;
#ifdef AGGREGATION
    prm.level.kcycle = 1;
#endif

    prof.tic("setup");
    amg_precond amg(A, prm);
    prof.toc("setup");

    // Copy matrix and rhs to GPU(s).
    viennacl::hyb_matrix<double> Agpu;
    viennacl::copy(amgcl::sparse::viennacl_map(A), Agpu);

    viennacl::vector<double> f(n);
    viennacl::fast_copy(rhs, f);

    // Solve the problem with CG method from ViennaCL. Use AMG as a
    // preconditioner:
    prof.tic("solve");
    viennacl::linalg::cg_tag tag(1e-8, 100);
    viennacl::vector<double> x = viennacl::linalg::solve(Agpu, f, tag, amg);
    prof.toc("solve");

    std::cout << "Iterations: " << tag.iters() << std::endl
              << "Error:      " << tag.error() << std::endl;

    std::cout << prof;

    // Prevent ViennaCL from segfaulting:
    exit(0);
}
<commit_msg>Support for OpenMP backend in ViennaCL<commit_after>#include <iostream>
#include <fstream>
#include <chrono>
#include <cstdlib>

#define VIENNACL_WITH_OPENCL
//#define VIENNACL_WITH_OPENMP

#define AMGCL_PROFILING

#include <amgcl/amgcl.hpp>
#include <amgcl/level_viennacl.hpp>

#ifdef VIENNACL_WITH_OPENCL
#  include <vexcl/devlist.hpp>
#  include <viennacl/hyb_matrix.hpp>
#  include <amgcl/aggregation.hpp>
#else
#  include <viennacl/compressed_matrix.hpp>
#  include <amgcl/interp_classic.hpp>
#endif

#include <viennacl/vector.hpp>
#include <viennacl/linalg/cg.hpp>

namespace amgcl {
profiler<> prof;
}
using amgcl::prof;

// Simple wrapper around amgcl::solver that provides ViennaCL's preconditioner
// interface.
struct amg_precond {
    typedef amgcl::solver<
        double, int,
#ifdef VIENNACL_WITH_OPENCL
        amgcl::interp::aggregation<amgcl::aggr::plain>,
        amgcl::level::ViennaCL<amgcl::level::CL_MATRIX_HYB>
#else
        amgcl::interp::classic,
        amgcl::level::ViennaCL<amgcl::level::CL_MATRIX_CRS>
#endif
        > AMG;
    typedef typename AMG::params params;

    // Build AMG hierarchy.
    template <class matrix>
    amg_precond(const matrix &A, const params &prm = params())
        : amg(A, prm), r(amgcl::sparse::matrix_rows(A))
    { }

    // Use one V-cycle with zero initial approximation as a preconditioning step.
    void apply(viennacl::vector<double> &x) const {
        r.clear();
        amg.apply(x, r);
        viennacl::copy(r, x);
    }

    // Build VexCL-based hierarchy:
    mutable AMG amg;
    mutable viennacl::vector<double> r;
};

int main(int argc, char *argv[]) {
    if (argc < 2) {
        std::cerr << "Usage: " << argv[0] << " <problem.dat>" << std::endl;
        return 1;
    }

#ifdef VIENNACL_WITH_OPENCL
    // There is no easy way to select compute device in ViennaCL, so just use
    // VexCL for that.
    vex::Context ctx(
            vex::Filter::Env &&
            vex::Filter::DoublePrecision &&
            vex::Filter::Count(1)
            );
    std::vector<cl_device_id> dev_id(1, ctx.queue(0).getInfo<CL_QUEUE_DEVICE>()());
    std::vector<cl_command_queue> queue_id(1, ctx.queue(0)());
    viennacl::ocl::setup_context(0, ctx.context(0)(), dev_id, queue_id);
    std::cout << ctx << std::endl;
#endif

    // Read matrix and rhs from a binary file.
    std::ifstream pfile(argv[1], std::ios::binary);
    int n;
    pfile.read((char*)&n, sizeof(int));

    std::vector<int> row(n + 1);
    pfile.read((char*)row.data(), row.size() * sizeof(int));

    std::vector<int>    col(row.back());
    std::vector<double> val(row.back());
    std::vector<double> rhs(n);

    pfile.read((char*)col.data(), col.size() * sizeof(int));
    pfile.read((char*)val.data(), val.size() * sizeof(double));
    pfile.read((char*)rhs.data(), rhs.size() * sizeof(double));

    // Wrap the matrix into amgcl::sparse::map:
    amgcl::sparse::matrix_map<double, int> A(
            n, n, row.data(), col.data(), val.data()
            );

    // Build the preconditioner.
    amg_precond::params prm;
#ifdef VIENNACL_WITH_OPENCL
    prm.level.kcycle = 1;
#endif

    prof.tic("setup");
    amg_precond amg(A, prm);
    prof.toc("setup");

    // Copy matrix and rhs to GPU(s).
    viennacl::hyb_matrix<double> Agpu;
    viennacl::copy(amgcl::sparse::viennacl_map(A), Agpu);

    viennacl::vector<double> f(n);
    viennacl::fast_copy(rhs, f);

    // Solve the problem with CG method from ViennaCL. Use AMG as a
    // preconditioner:
    prof.tic("solve");
    viennacl::linalg::cg_tag tag(1e-8, 100);
    viennacl::vector<double> x = viennacl::linalg::solve(Agpu, f, tag, amg);
    prof.toc("solve");

    std::cout << "Iterations: " << tag.iters() << std::endl
              << "Error:      " << tag.error() << std::endl;

    std::cout << prof;

    // Prevent ViennaCL from segfaulting:
    exit(0);
}
<|endoftext|>


<commit_before>#include "frames.h"

frameGPUi::frameGPUi (int w, int h, bool full) {
	glGenTextures (1, &plane);
	glBindTexture (GL_TEXTURE_2D, plane);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexImage2D (GL_TEXTURE_2D, 0, full ? GL_RGBA32F : GL_RGBA16F, w, h, 0, GL_RGBA, full ? GL_FLOAT : GL_HALF_FLOAT, NULL);

	timecode = 0;
}

frameGPUi::~frameGPUi () {
	glDeleteTextures (1, &plane);
}
<commit_msg>10-bit normalased internal frames<commit_after>#include "frames.h"

frameGPUi::frameGPUi (int w, int h, bool full) {
	glGenTextures (1, &plane);
	glBindTexture (GL_TEXTURE_2D, plane);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	//glTexImage2D (GL_TEXTURE_2D, 0, full ? GL_RGBA32F : GL_RGBA16F, w, h, 0, GL_RGBA, full ? GL_FLOAT : GL_HALF_FLOAT, NULL);
	glTexImage2D (GL_TEXTURE_2D, 0, GL_RGB10_A2, w, h, 0, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, NULL);
	timecode = 0;
}

frameGPUi::~frameGPUi () {
	glDeleteTextures (1, &plane);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: valueproperties.cxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: fs $ $Date: 2000-12-13 10:36:36 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLOFF_FORMS_VALUEPROPERTIES_HXX_
#include "valueproperties.hxx"
#endif
#ifndef _XMLOFF_FORMS_STRINGS_HXX_
#include "strings.hxx"
#endif
#ifndef _COM_SUN_STAR_FORM_FORMCOMPONENTTYPE_HPP_
#include <com/sun/star/form/FormComponentType.hpp>
#endif

//.........................................................................
namespace xmloff
{
//.........................................................................

    using namespace ::com::sun::star::form;

    //=====================================================================
    //= OValuePropertiesMetaData
    //=====================================================================
    //---------------------------------------------------------------------
    void OValuePropertiesMetaData::getValuePropertyNames(
            OControlElement::ElementType _eType, sal_Int16 _nFormComponentType,
            sal_Char const * & _rpCurrentValuePropertyName, sal_Char const * & _rpValuePropertyName)
    {
        // reset the pointers in case we can't determine the property names
        _rpCurrentValuePropertyName = _rpValuePropertyName = NULL;
        switch (_nFormComponentType)
        {
            case FormComponentType::TEXTFIELD:
                if (OControlElement::FORMATTED_TEXT == _eType)
                {
                    _rpCurrentValuePropertyName = PROPERTY_EFFECTIVE_VALUE;
                    _rpValuePropertyName = PROPERTY_EFFECTIVE_DEFAULT;
                }
                else
                {
                    _rpCurrentValuePropertyName = PROPERTY_TEXT;
                    _rpValuePropertyName = PROPERTY_DEFAULT_TEXT;
                }
                break;
            case FormComponentType::DATEFIELD:
                _rpCurrentValuePropertyName = PROPERTY_DATE;
                _rpValuePropertyName = PROPERTY_DEFAULT_DATE;
                break;
            case FormComponentType::TIMEFIELD:
                _rpCurrentValuePropertyName = PROPERTY_TIME;
                _rpValuePropertyName = PROPERTY_DEFAULT_TIME;
                break;
            case FormComponentType::NUMERICFIELD:
            case FormComponentType::CURRENCYFIELD:
                _rpCurrentValuePropertyName = PROPERTY_VALUE;
                _rpValuePropertyName = PROPERTY_DEFAULT_VALUE;
                break;
            case FormComponentType::PATTERNFIELD:
            case FormComponentType::FILECONTROL:
            case FormComponentType::COMBOBOX:
                _rpValuePropertyName = PROPERTY_DEFAULT_TEXT;
                // NO BREAK!!
            case FormComponentType::COMMANDBUTTON:
                _rpCurrentValuePropertyName = PROPERTY_TEXT;
                break;
            case FormComponentType::CHECKBOX:
            case FormComponentType::RADIOBUTTON:
                _rpValuePropertyName = PROPERTY_REFVALUE;
                break;
            case FormComponentType::HIDDENCONTROL:
                _rpValuePropertyName = PROPERTY_VALUE;
                break;
        }
    }

    //---------------------------------------------------------------------
    void OValuePropertiesMetaData::getValueLimitPropertyNames(sal_Int16 _nFormComponentType,
        sal_Char const * & _rpMinValuePropertyName, sal_Char const * & _rpMaxValuePropertyName)
    {
        _rpMinValuePropertyName = _rpMinValuePropertyName = NULL;
        switch (_nFormComponentType)
        {
            case FormComponentType::DATEFIELD:
                _rpMinValuePropertyName = PROPERTY_DATE_MIN;
                _rpMaxValuePropertyName = PROPERTY_DATE_MAX;
                break;
            case FormComponentType::TIMEFIELD:
                _rpMinValuePropertyName = PROPERTY_TIME_MIN;
                _rpMaxValuePropertyName = PROPERTY_TIME_MAX;
                break;
            case FormComponentType::NUMERICFIELD:
            case FormComponentType::CURRENCYFIELD:
                _rpMinValuePropertyName = PROPERTY_VALUE_MIN;
                _rpMaxValuePropertyName = PROPERTY_VALUE_MAX;
                break;
            case FormComponentType::PATTERNFIELD:
                // no min/max value for the pattern field
                break;
            case FormComponentType::TEXTFIELD:
                _rpMinValuePropertyName = PROPERTY_EFFECTIVE_MIN;
                _rpMaxValuePropertyName = PROPERTY_EFFECTIVE_MAX;
                break;
        }
    }

//.........................................................................
}   // namespace xmloff
//.........................................................................

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *
 *  Revision 1.0 12.12.00 14:14:36  fs
 ************************************************************************/

<commit_msg>#83528# no CurrentValue property for password fields<commit_after>/*************************************************************************
 *
 *  $RCSfile: valueproperties.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: fs $ $Date: 2001-02-13 09:07:25 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLOFF_FORMS_VALUEPROPERTIES_HXX_
#include "valueproperties.hxx"
#endif
#ifndef _XMLOFF_FORMS_STRINGS_HXX_
#include "strings.hxx"
#endif
#ifndef _COM_SUN_STAR_FORM_FORMCOMPONENTTYPE_HPP_
#include <com/sun/star/form/FormComponentType.hpp>
#endif

//.........................................................................
namespace xmloff
{
//.........................................................................

    using namespace ::com::sun::star::form;

    //=====================================================================
    //= OValuePropertiesMetaData
    //=====================================================================
    //---------------------------------------------------------------------
    void OValuePropertiesMetaData::getValuePropertyNames(
            OControlElement::ElementType _eType, sal_Int16 _nFormComponentType,
            sal_Char const * & _rpCurrentValuePropertyName, sal_Char const * & _rpValuePropertyName)
    {
        // reset the pointers in case we can't determine the property names
        _rpCurrentValuePropertyName = _rpValuePropertyName = NULL;
        switch (_nFormComponentType)
        {
            case FormComponentType::TEXTFIELD:
                if (OControlElement::FORMATTED_TEXT == _eType)
                {
                    _rpCurrentValuePropertyName = PROPERTY_EFFECTIVE_VALUE;
                    _rpValuePropertyName = PROPERTY_EFFECTIVE_DEFAULT;
                }
                else
                {
                    if (OControlElement::PASSWORD != _eType)
                        // no CurrentValue" for passwords
                        _rpCurrentValuePropertyName = PROPERTY_TEXT;
                    _rpValuePropertyName = PROPERTY_DEFAULT_TEXT;
                }
                break;
            case FormComponentType::DATEFIELD:
                _rpCurrentValuePropertyName = PROPERTY_DATE;
                _rpValuePropertyName = PROPERTY_DEFAULT_DATE;
                break;
            case FormComponentType::TIMEFIELD:
                _rpCurrentValuePropertyName = PROPERTY_TIME;
                _rpValuePropertyName = PROPERTY_DEFAULT_TIME;
                break;
            case FormComponentType::NUMERICFIELD:
            case FormComponentType::CURRENCYFIELD:
                _rpCurrentValuePropertyName = PROPERTY_VALUE;
                _rpValuePropertyName = PROPERTY_DEFAULT_VALUE;
                break;
            case FormComponentType::PATTERNFIELD:
            case FormComponentType::FILECONTROL:
            case FormComponentType::COMBOBOX:
                _rpValuePropertyName = PROPERTY_DEFAULT_TEXT;
                // NO BREAK!!
            case FormComponentType::COMMANDBUTTON:
                _rpCurrentValuePropertyName = PROPERTY_TEXT;
                break;
            case FormComponentType::CHECKBOX:
            case FormComponentType::RADIOBUTTON:
                _rpValuePropertyName = PROPERTY_REFVALUE;
                break;
            case FormComponentType::HIDDENCONTROL:
                _rpValuePropertyName = PROPERTY_VALUE;
                break;
        }
    }

    //---------------------------------------------------------------------
    void OValuePropertiesMetaData::getValueLimitPropertyNames(sal_Int16 _nFormComponentType,
        sal_Char const * & _rpMinValuePropertyName, sal_Char const * & _rpMaxValuePropertyName)
    {
        _rpMinValuePropertyName = _rpMinValuePropertyName = NULL;
        switch (_nFormComponentType)
        {
            case FormComponentType::DATEFIELD:
                _rpMinValuePropertyName = PROPERTY_DATE_MIN;
                _rpMaxValuePropertyName = PROPERTY_DATE_MAX;
                break;
            case FormComponentType::TIMEFIELD:
                _rpMinValuePropertyName = PROPERTY_TIME_MIN;
                _rpMaxValuePropertyName = PROPERTY_TIME_MAX;
                break;
            case FormComponentType::NUMERICFIELD:
            case FormComponentType::CURRENCYFIELD:
                _rpMinValuePropertyName = PROPERTY_VALUE_MIN;
                _rpMaxValuePropertyName = PROPERTY_VALUE_MAX;
                break;
            case FormComponentType::PATTERNFIELD:
                // no min/max value for the pattern field
                break;
            case FormComponentType::TEXTFIELD:
                _rpMinValuePropertyName = PROPERTY_EFFECTIVE_MIN;
                _rpMaxValuePropertyName = PROPERTY_EFFECTIVE_MAX;
                break;
        }
    }

//.........................................................................
}   // namespace xmloff
//.........................................................................

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *  Revision 1.1  2000/12/13 10:36:36  fs
 *  initial checkin - helper class for meta data for the different value properties
 *
 *
 *  Revision 1.0 12.12.00 14:14:36  fs
 ************************************************************************/

<|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: saxhelper.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 _SAXHELPER_HXX
#define _SAXHELPER_HXX

#include "libxml/tree.h"

#include <com/sun/star/xml/sax/SAXException.hpp>
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#include <com/sun/star/xml/sax/XLocator.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/xml/csax/XMLAttribute.hpp>

class SAXHelper
{
    private :
        xmlParserCtxtPtr m_pParserCtxt ;
        xmlSAXHandlerPtr m_pSaxHandler ;

    public:
        SAXHelper( ) ;
        virtual ~SAXHelper() ;

        xmlNodePtr getCurrentNode();
        void setCurrentNode(const xmlNodePtr pNode);
        xmlDocPtr getDocument();

        void startDocument( void )
            throw( ::com::sun::star::xml::sax::SAXException , ::com::sun::star::uno::RuntimeException ) ;

        void endDocument( void )
            throw( ::com::sun::star::xml::sax::SAXException , ::com::sun::star::uno::RuntimeException ) ;

        void startElement(
            const ::rtl::OUString& aName ,
            const com::sun::star::uno::Sequence<
                com::sun::star::xml::csax::XMLAttribute >& aAttributes )
            throw( ::com::sun::star::xml::sax::SAXException , ::com::sun::star::uno::RuntimeException ) ;

        void endElement( const ::rtl::OUString& aName )
            throw( ::com::sun::star::xml::sax::SAXException , ::com::sun::star::uno::RuntimeException ) ;

        void characters( const ::rtl::OUString& aChars )
            throw( ::com::sun::star::xml::sax::SAXException , ::com::sun::star::uno::RuntimeException ) ;

        void ignorableWhitespace( const ::rtl::OUString& aWhitespaces )
            throw( ::com::sun::star::xml::sax::SAXException , ::com::sun::star::uno::RuntimeException ) ;

        void processingInstruction(
            const ::rtl::OUString& aTarget ,
            const ::rtl::OUString& aData )
            throw( ::com::sun::star::xml::sax::SAXException , ::com::sun::star::uno::RuntimeException ) ;

        void setDocumentLocator( const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XLocator > & xLocator )
            throw( ::com::sun::star::xml::sax::SAXException , ::com::sun::star::uno::RuntimeException ) ;
} ;

#endif

<commit_msg>INTEGRATION: CWS jl103 (1.3.16); FILE MERGED 2008/06/13 07:28:39 jl 1.3.16.1: #i86233# uri encoding the URI attribute of the reference elements<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: saxhelper.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 _SAXHELPER_HXX
#define _SAXHELPER_HXX

#include "libxml/tree.h"

#include <com/sun/star/xml/sax/SAXException.hpp>
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#include <com/sun/star/xml/sax/XLocator.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/xml/csax/XMLAttribute.hpp>

/** This class represents a SAX handler which simply forwards to
    the corresponding libxml API and translates parameter if necessary.
*/
class SAXHelper
{
    private :
        xmlParserCtxtPtr m_pParserCtxt ;
        xmlSAXHandlerPtr m_pSaxHandler ;

    public:
        SAXHelper( ) ;
        virtual ~SAXHelper() ;

        xmlNodePtr getCurrentNode();
        void setCurrentNode(const xmlNodePtr pNode);
        xmlDocPtr getDocument();

        void startDocument( void )
            throw( ::com::sun::star::xml::sax::SAXException , ::com::sun::star::uno::RuntimeException ) ;

        void endDocument( void )
            throw( ::com::sun::star::xml::sax::SAXException , ::com::sun::star::uno::RuntimeException ) ;

        void startElement(
            const ::rtl::OUString& aName ,
            const com::sun::star::uno::Sequence<
                com::sun::star::xml::csax::XMLAttribute >& aAttributes )
            throw( ::com::sun::star::xml::sax::SAXException , ::com::sun::star::uno::RuntimeException ) ;

        void endElement( const ::rtl::OUString& aName )
            throw( ::com::sun::star::xml::sax::SAXException , ::com::sun::star::uno::RuntimeException ) ;

        void characters( const ::rtl::OUString& aChars )
            throw( ::com::sun::star::xml::sax::SAXException , ::com::sun::star::uno::RuntimeException ) ;

        void ignorableWhitespace( const ::rtl::OUString& aWhitespaces )
            throw( ::com::sun::star::xml::sax::SAXException , ::com::sun::star::uno::RuntimeException ) ;

        void processingInstruction(
            const ::rtl::OUString& aTarget ,
            const ::rtl::OUString& aData )
            throw( ::com::sun::star::xml::sax::SAXException , ::com::sun::star::uno::RuntimeException ) ;

        void setDocumentLocator( const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XLocator > & xLocator )
            throw( ::com::sun::star::xml::sax::SAXException , ::com::sun::star::uno::RuntimeException ) ;
} ;

#endif

<|endoftext|>


<commit_before>// Copyright 2016 Jonathan Buchanan.
// This file is part of Sunglasses, which is licensed under the MIT License.
// See LICENSE.md for details.
#include "SunCamera.h"
#include "SunMesh.h"
#include "SunModel.h"
#include "SunPrimitives.h"
#include "SunRenderer.h"
#include "SunShader.h"
#include "SunTextRenderer.h"
#include "SunTexturedQuad.h"
#include "SunUniformPasser.h"
#include "SunWindowManager.h"
<commit_msg>Fixed Graphics.hpp<commit_after>// Copyright 2016 Jonathan Buchanan.
// This file is part of Sunglasses, which is licensed under the MIT License.
// See LICENSE.md for details.
#include "SunCamera.h"
#include "SunMesh.h"
#include "SunModel.h"
#include "SunPrimitives.h"
#include "SunRenderer.h"
#include "SunShader.h"
#include "SunTexturedQuad.h"
#include "SunUniformPasser.h"
#include "SunWindowManager.h"
<|endoftext|>


<commit_before>// this file defines the FilterExamples for the test driver
// and all it expects is that you have a function called RegisterTests
#include <iostream>
#include "itkTestMain.h"

void RegisterTests()
{
REGISTER_TEST(BilateralImageFilterTest);
REGISTER_TEST(BinaryMinMaxCurvatureFlowImageFilterTest);
REGISTER_TEST(BinaryThresholdImageFilterTest);
REGISTER_TEST(BinomialBlurImageFilterTest);
REGISTER_TEST(CastingImageFiltersTest);
REGISTER_TEST(CurvatureAnisotropicDiffusionImageFilterTest);
REGISTER_TEST(CurvatureFlowImageFilterTest);
REGISTER_TEST(DanielssonDistanceMapImageFilterTest);
REGISTER_TEST(DerivativeImageFilterTest);
REGISTER_TEST(DiscreteGaussianImageFilterTest);
REGISTER_TEST(GradientAnisotropicDiffusionImageFilterTest);
REGISTER_TEST(GradientMagnitudeImageFilterTest);
REGISTER_TEST(GradientMagnitudeRecursiveGaussianImageFilterTest);
REGISTER_TEST(LaplacianImageFilterTest);
REGISTER_TEST(MathematicalMorphologyBinaryFiltersTest);
REGISTER_TEST(MathematicalMorphologyGrayscaleFiltersTest);
REGISTER_TEST(MeanImageFilterTest);
REGISTER_TEST(MedianImageFilterTest);
REGISTER_TEST(MinMaxCurvatureFlowImageFilterTest);
REGISTER_TEST(RGBCurvatureAnisotropicDiffusionImageFilterTest);
REGISTER_TEST(RGBGradientAnisotropicDiffusionImageFilterTest);
REGISTER_TEST(ResampleImageFilterTest);
REGISTER_TEST(ResampleImageFilter2Test);
REGISTER_TEST(ResampleImageFilter3Test);
REGISTER_TEST(ResampleImageFilter4Test);
REGISTER_TEST(ResampleImageFilter5Test);
REGISTER_TEST(SigmoidImageFilterTest);
REGISTER_TEST(SmoothingRecursiveGaussianImageFilterTest);
REGISTER_TEST(ThresholdImageFilterTest);
REGISTER_TEST(VectorCurvatureAnisotropicDiffusionImageFilterTest);
REGISTER_TEST(VectorGradientAnisotropicDiffusionImageFilterTest);
}

#undef main
#define main BilateralImageFilterTest
#include "BilateralImageFilter.cxx"

#undef main
#define main BinaryMinMaxCurvatureFlowImageFilterTest
#include "BinaryMinMaxCurvatureFlowImageFilter.cxx"

#undef main
#define main BinaryThresholdImageFilterTest
#include "BinaryThresholdImageFilter.cxx"

#undef main
#define main BinomialBlurImageFilterTest
#include "BinomialBlurImageFilter.cxx"

#undef main
#define main CastingImageFiltersTest
#include "CastingImageFilters.cxx"

#undef main
#define main CurvatureAnisotropicDiffusionImageFilterTest
#include "CurvatureAnisotropicDiffusionImageFilter.cxx"

#undef main
#define main CurvatureFlowImageFilterTest
#include "CurvatureFlowImageFilter.cxx"

#undef main
#define main DanielssonDistanceMapImageFilterTest
#include "DanielssonDistanceMapImageFilter.cxx"

#undef main
#define main DiscreteGaussianImageFilterTest
#include "DiscreteGaussianImageFilter.cxx"

#undef main
#define main DerivativeImageFilterTest
#include "DerivativeImageFilter.cxx"

#undef main
#define main GradientAnisotropicDiffusionImageFilterTest
#include "GradientAnisotropicDiffusionImageFilter.cxx"

#undef main
#define main GradientMagnitudeImageFilterTest
#include "GradientMagnitudeImageFilter.cxx"

#undef main
#define main GradientMagnitudeRecursiveGaussianImageFilterTest
#include "GradientMagnitudeRecursiveGaussianImageFilter.cxx"

#undef main
#define main LaplacianImageFilterTest
#include "LaplacianImageFilter.cxx"

#undef main
#define main MathematicalMorphologyBinaryFiltersTest
#include "MathematicalMorphologyBinaryFilters.cxx"

#undef main
#define main MathematicalMorphologyGrayscaleFiltersTest
#include "MathematicalMorphologyGrayscaleFilters.cxx"

#undef main
#define main MeanImageFilterTest
#include "MeanImageFilter.cxx"

#undef main
#define main MedianImageFilterTest
#include "MedianImageFilter.cxx"

#undef main
#define main MinMaxCurvatureFlowImageFilterTest
#include "MinMaxCurvatureFlowImageFilter.cxx"

#undef main
#define main RGBCurvatureAnisotropicDiffusionImageFilterTest
#include "RGBCurvatureAnisotropicDiffusionImageFilter.cxx"

#undef main
#define main RGBGradientAnisotropicDiffusionImageFilterTest
#include "RGBGradientAnisotropicDiffusionImageFilter.cxx"

#undef main
#define main ResampleImageFilterTest
#include "ResampleImageFilter.cxx"

#undef main
#define main ResampleImageFilter2Test
#include "ResampleImageFilter2.cxx"

#undef main
#define main ResampleImageFilter3Test
#include "ResampleImageFilter3.cxx"

#undef main
#define main ResampleImageFilter4Test
#include "ResampleImageFilter4.cxx"

#undef main
#define main ResampleImageFilter5Test
#include "ResampleImageFilter5.cxx"

#undef main
#define main SigmoidImageFilterTest
#include "SigmoidImageFilter.cxx"

#undef main
#define main SmoothingRecursiveGaussianImageFilterTest
#include "SmoothingRecursiveGaussianImageFilter.cxx"

#undef main
#define main ThresholdImageFilterTest
#include "ThresholdImageFilter.cxx"

#undef main
#define main VectorCurvatureAnisotropicDiffusionImageFilterTest
#include "VectorCurvatureAnisotropicDiffusionImageFilter.cxx"

#undef main
#define main VectorGradientAnisotropicDiffusionImageFilterTest
#include "VectorGradientAnisotropicDiffusionImageFilter.cxx"
<commit_msg>FIX: DerivativeImageFilter test added.<commit_after>// this file defines the FilterExamples for the test driver
// and all it expects is that you have a function called RegisterTests
#include <iostream>
#include "itkTestMain.h"

void RegisterTests()
{
REGISTER_TEST(BilateralImageFilterTest);
REGISTER_TEST(BinaryMinMaxCurvatureFlowImageFilterTest);
REGISTER_TEST(BinaryThresholdImageFilterTest);
REGISTER_TEST(BinomialBlurImageFilterTest);
REGISTER_TEST(CastingImageFiltersTest);
REGISTER_TEST(CurvatureAnisotropicDiffusionImageFilterTest);
REGISTER_TEST(CurvatureFlowImageFilterTest);
REGISTER_TEST(DanielssonDistanceMapImageFilterTest);
REGISTER_TEST(DerivativeImageFilterTest);
REGISTER_TEST(DiscreteGaussianImageFilterTest);
REGISTER_TEST(GradientAnisotropicDiffusionImageFilterTest);
REGISTER_TEST(GradientMagnitudeImageFilterTest);
REGISTER_TEST(GradientMagnitudeRecursiveGaussianImageFilterTest);
REGISTER_TEST(LaplacianImageFilterTest);
REGISTER_TEST(MathematicalMorphologyBinaryFiltersTest);
REGISTER_TEST(MathematicalMorphologyGrayscaleFiltersTest);
REGISTER_TEST(MeanImageFilterTest);
REGISTER_TEST(MedianImageFilterTest);
REGISTER_TEST(MinMaxCurvatureFlowImageFilterTest);
REGISTER_TEST(RGBCurvatureAnisotropicDiffusionImageFilterTest);
REGISTER_TEST(RGBGradientAnisotropicDiffusionImageFilterTest);
REGISTER_TEST(ResampleImageFilterTest);
REGISTER_TEST(ResampleImageFilter2Test);
REGISTER_TEST(ResampleImageFilter3Test);
REGISTER_TEST(ResampleImageFilter4Test);
REGISTER_TEST(ResampleImageFilter5Test);
REGISTER_TEST(SigmoidImageFilterTest);
REGISTER_TEST(SmoothingRecursiveGaussianImageFilterTest);
REGISTER_TEST(ThresholdImageFilterTest);
REGISTER_TEST(VectorCurvatureAnisotropicDiffusionImageFilterTest);
REGISTER_TEST(VectorGradientAnisotropicDiffusionImageFilterTest);
}

#undef main
#define main BilateralImageFilterTest
#include "BilateralImageFilter.cxx"

#undef main
#define main BinaryMinMaxCurvatureFlowImageFilterTest
#include "BinaryMinMaxCurvatureFlowImageFilter.cxx"

#undef main
#define main BinaryThresholdImageFilterTest
#include "BinaryThresholdImageFilter.cxx"

#undef main
#define main BinomialBlurImageFilterTest
#include "BinomialBlurImageFilter.cxx"

#undef main
#define main CastingImageFiltersTest
#include "CastingImageFilters.cxx"

#undef main
#define main CurvatureAnisotropicDiffusionImageFilterTest
#include "CurvatureAnisotropicDiffusionImageFilter.cxx"

#undef main
#define main CurvatureFlowImageFilterTest
#include "CurvatureFlowImageFilter.cxx"

#undef main
#define main DanielssonDistanceMapImageFilterTest
#include "DanielssonDistanceMapImageFilter.cxx"

#undef main
#define main DerivativeImageFilterTest
#include "DerivativeImageFilter.cxx"

#undef main
#define main DiscreteGaussianImageFilterTest
#include "DiscreteGaussianImageFilter.cxx"

#undef main
#define main DerivativeImageFilterTest
#include "DerivativeImageFilter.cxx"

#undef main
#define main GradientAnisotropicDiffusionImageFilterTest
#include "GradientAnisotropicDiffusionImageFilter.cxx"

#undef main
#define main GradientMagnitudeImageFilterTest
#include "GradientMagnitudeImageFilter.cxx"

#undef main
#define main GradientMagnitudeRecursiveGaussianImageFilterTest
#include "GradientMagnitudeRecursiveGaussianImageFilter.cxx"

#undef main
#define main LaplacianImageFilterTest
#include "LaplacianImageFilter.cxx"

#undef main
#define main MathematicalMorphologyBinaryFiltersTest
#include "MathematicalMorphologyBinaryFilters.cxx"

#undef main
#define main MathematicalMorphologyGrayscaleFiltersTest
#include "MathematicalMorphologyGrayscaleFilters.cxx"

#undef main
#define main MeanImageFilterTest
#include "MeanImageFilter.cxx"

#undef main
#define main MedianImageFilterTest
#include "MedianImageFilter.cxx"

#undef main
#define main MinMaxCurvatureFlowImageFilterTest
#include "MinMaxCurvatureFlowImageFilter.cxx"

#undef main
#define main RGBCurvatureAnisotropicDiffusionImageFilterTest
#include "RGBCurvatureAnisotropicDiffusionImageFilter.cxx"

#undef main
#define main RGBGradientAnisotropicDiffusionImageFilterTest
#include "RGBGradientAnisotropicDiffusionImageFilter.cxx"

#undef main
#define main ResampleImageFilterTest
#include "ResampleImageFilter.cxx"

#undef main
#define main ResampleImageFilter2Test
#include "ResampleImageFilter2.cxx"

#undef main
#define main ResampleImageFilter3Test
#include "ResampleImageFilter3.cxx"

#undef main
#define main ResampleImageFilter4Test
#include "ResampleImageFilter4.cxx"

#undef main
#define main ResampleImageFilter5Test
#include "ResampleImageFilter5.cxx"

#undef main
#define main SigmoidImageFilterTest
#include "SigmoidImageFilter.cxx"

#undef main
#define main SmoothingRecursiveGaussianImageFilterTest
#include "SmoothingRecursiveGaussianImageFilter.cxx"

#undef main
#define main ThresholdImageFilterTest
#include "ThresholdImageFilter.cxx"

#undef main
#define main VectorCurvatureAnisotropicDiffusionImageFilterTest
#include "VectorCurvatureAnisotropicDiffusionImageFilter.cxx"

#undef main
#define main VectorGradientAnisotropicDiffusionImageFilterTest
#include "VectorGradientAnisotropicDiffusionImageFilter.cxx"
<|endoftext|>


<commit_before>#include "c_dbxml.h"
#include <dbxml/DbXml.hpp>
#include <string>

#define ALIAS "c_dbxml"

extern "C" {

    struct c_dbxml_t {
	DbXml::XmlManager manager;
	DbXml::XmlUpdateContext context;
	DbXml::XmlContainer container;
	DbXml::XmlContainerConfig config;
	bool error;
	std::string filename;
	std::string errstring;
    };

    struct c_dbxml_result_t {
	std::string result;
	bool error;
    };

    struct c_dbxml_docs_t {
	DbXml::XmlDocument doc;
	DbXml::XmlValue value;
	DbXml::XmlResults it;
	DbXml::XmlQueryContext context;
	bool more;
	std::string name;
	std::string content;
	std::string match;
	bool error;
	std::string errstring;
    };

    struct c_dbxml_query_t {
	DbXml::XmlQueryContext context;
	DbXml::XmlQueryExpression expression;
	bool error;
	std::string errstring;
    };

    c_dbxml c_dbxml_open(char const *filename, int readwrite, int read)
    {
	c_dbxml db;

	db = new c_dbxml_t;
	db->filename = filename;

	for (int i = 0; i < 2; i++) {
	    /* if both: first attempt is read+write */
	    if (i == 0 && readwrite == 0) {
		continue;
	    }
	    if (i == 1 && read == 0) {
		continue;
	    }
	    try {
		db->context = db->manager.createUpdateContext();
		if (i == 0) {
		    db->config.setAllowCreate(true);
		    db->config.setMode(0666);
		} else {
		    db->config.setReadOnly(true);
		}
		db->container = db->manager.openContainer(filename, db->config);
		db->error = false;
		if (!db->container.addAlias(ALIAS)) {
		    db->errstring = "Unable to add alias \"" ALIAS "\"";
		    db->error = true;
		}
	    } catch (DbXml::XmlException &xe) {
		db->errstring = xe.what();
		db->error = true;
	    }
	    if (db->error == false) {
		break;
	    }
	}

	return db;
    }

    void c_dbxml_free(c_dbxml db)
    {
	delete db;
    }

    int c_dbxml_error(c_dbxml db)
    {
	return db->error ? 1 : 0;
    }

    char const *c_dbxml_errstring(c_dbxml db)
    {
	return db->errstring.c_str();
    }

    void c_dbxml_result_free(c_dbxml_result r)
    {
	delete r;
    }

    int c_dbxml_result_error(c_dbxml_result r)
    {
	return r->error ? 1 : 0;
    }

    char const *c_dbxml_result_string(c_dbxml_result r)
    {
	return r->result.c_str();
    }

    c_dbxml_result c_dbxml_put_file(c_dbxml db, char const * filename, int replace)
    {
	c_dbxml_result r;
	r = new c_dbxml_result_t;

	if (replace) {
	    try {
		db->container.deleteDocument(filename, db->context);
	    } catch (DbXml::XmlException &xe) {
		;
	    }
	}
        try {
            DbXml::XmlInputStream *is = db->manager.createLocalFileInputStream(filename);
            db->container.putDocument(filename, is, db->context, DbXml::DBXML_WELL_FORMED_ONLY);
	    r->error = false;
        } catch (DbXml::XmlException &xe) {
	    r->result = xe.what();
	    r->error = true;
        }

	return r;
    }

    // replace if replace != 0
    c_dbxml_result c_dbxml_put_xml(c_dbxml db, char const *name, char const *data, int replace)
    {
	c_dbxml_result r;
	r = new c_dbxml_result_t;

	if (replace) {
	    try {
		db->container.deleteDocument(name, db->context);
	    } catch (DbXml::XmlException &xe) {
		;
	    }
	}

        try {
            db->container.putDocument(name, data, db->context);
	    r->error = false;
        } catch (DbXml::XmlException &xe) {
	    r->result = xe.what();
	    r->error = true;
        }
	return r;
    }

    // replace if replace != 0
    c_dbxml_result c_dbxml_merge(c_dbxml db, char const * dbxmlfile, int replace) {
	c_dbxml_result r;
	r = new c_dbxml_result_t;

	DbXml::XmlContainer input = db->manager.openContainer(dbxmlfile);
	DbXml::XmlDocument doc;
	DbXml::XmlResults it = input.getAllDocuments(DbXml::DBXML_LAZY_DOCS);
	while (it.next(doc)) {
	    if (replace) {
		try {
		    db->container.deleteDocument(doc.getName(), db->context);
		} catch (DbXml::XmlException &xe) {
		    ;
		}
	    }
	    try {
		db->container.putDocument(doc, db->context);
		r->error = false;
	    } catch (DbXml::XmlException &xe) {
		r->result = xe.what();
		r->error = true;
		return r;
	    }
	}
	return r;
    }

    c_dbxml_result c_dbxml_remove(c_dbxml db, char const * filename)
    {
	c_dbxml_result r;
	r = new c_dbxml_result_t;

	try {
	    db->container.deleteDocument(filename, db->context);
	    r->error = false;
        } catch (DbXml::XmlException &xe) {
	    r->result = xe.what();
	    r->error = true;
	}
	return r;
    }

    c_dbxml_result c_dbxml_get(c_dbxml db, char const * name)
    {
	c_dbxml_result r;
	r = new c_dbxml_result_t;
	try {
	    DbXml::XmlDocument doc = db->container.getDocument(name);
	    doc.getContent(r->result);
	    r->error = false;
	} catch (DbXml::XmlException &xe) {
	    r->result = xe.what();
	    r->error = true;
	}
	return r;
    }

    unsigned long long c_dbxml_size(c_dbxml db)
    {
	return (unsigned long long) db->container.getNumDocuments();
    }

    c_dbxml_docs c_dbxml_get_all(c_dbxml db)
    {
	c_dbxml_docs docs;
	docs = new c_dbxml_docs_t;
	docs->it = db->container.getAllDocuments(DbXml::DBXML_LAZY_DOCS);
	docs->more = true;
	docs->error = false;
	return docs;
    }

    c_dbxml_query c_dbxml_prepare_query(c_dbxml db, char const *query)
    {
	c_dbxml_query q;
	q = new c_dbxml_query_t;
	try {
	    q->context = db->manager.createQueryContext(DbXml::XmlQueryContext::LiveValues, DbXml::XmlQueryContext::Lazy);
	    q->context.setDefaultCollection(ALIAS);
	    q->expression = db->manager.prepare(std::string("collection('" ALIAS "')") + query, q->context);
	    q->error = false;
	    if (q->expression.isUpdateExpression()) {
		q->errstring = "Update Expressions are not allowed";
		q->error = true;
	    }
	} catch (DbXml::XmlException const &xe) {
	    q->errstring = xe.what();
	    q->error = true;
	}
	return q;
    }

    c_dbxml_docs c_dbxml_run_query(c_dbxml_query query)
    {
	c_dbxml_docs docs;
	docs = new c_dbxml_docs_t;
	docs->more = true;
	docs->context = query->context;
	try {
	    docs->it = query->expression.execute(docs->context,
						 DbXml::DBXML_LAZY_DOCS | DbXml::DBXML_WELL_FORMED_ONLY
						 );
	    docs->error = false;
	} catch (DbXml::XmlException const &xe) {
	    docs->more = false;
	    docs->errstring = xe.what();
	    docs->error = true;
	}

	return docs;
    }

    int c_dbxml_get_query_error(c_dbxml_docs docs)
    {
	return docs->error ? 1 : 0;
    }

    char const *c_dbxml_get_query_errstring(c_dbxml_docs docs)
    {
	return docs->errstring.c_str();
    }

    int c_dbxml_get_prepared_error(c_dbxml_query query)
    {
	return query->error ? 1 : 0;
    }

    char const *c_dbxml_get_prepared_errstring(c_dbxml_query query)
    {
	return query->errstring.c_str();
    }

    int c_dbxml_docs_next(c_dbxml_docs docs)
    {
	if (docs->more) {
	    try {
		docs->it.peek(docs->value);
		docs->more = docs->it.next(docs->doc);
	    } catch (DbXml::XmlException &xe) {
		docs->errstring = xe.what();
		docs->error = true;
		docs->more = false;
	    }
	    docs->name.clear();
	    docs->content.clear();
	    docs->match.clear();
	}
	return docs->more ? 1 : 0;
    }

    char const * c_dbxml_docs_name(c_dbxml_docs docs)
    {
	if (docs->more && ! docs->name.size())
	    docs->name = docs->doc.getName();

	return docs->name.c_str();
    }

    char const * c_dbxml_docs_content(c_dbxml_docs docs)
    {
	if (docs->more && ! docs->content.size())
	    docs->doc.getContent(docs->content);

	return docs->content.c_str();
    }

    char const * c_dbxml_docs_match(c_dbxml_docs docs)
    {
	if (docs->more && ! docs->match.size() && docs->value.isNode()) {
	    docs->match = docs->value.asString();
	}

	return docs->match.c_str();
    }

    void c_dbxml_docs_free(c_dbxml_docs docs)
    {
	delete docs;
    }

    void c_dbxml_query_free(c_dbxml_query query)
    {
	delete query;
    }

    void c_dbxml_cancel_query(c_dbxml_query query)
    {
	query->context.interruptQuery();
    }

    c_dbxml_result c_dbxml_check(char const *query)
    {
	c_dbxml_result r;
	r = new c_dbxml_result_t;
	try {
	    DbXml::XmlManager manager;
	    DbXml::XmlQueryContext context;
	    DbXml::XmlQueryExpression expr;
	    context = manager.createQueryContext(DbXml::XmlQueryContext::LiveValues, DbXml::XmlQueryContext::Lazy);
	    expr = manager.prepare(std::string(query), context);
	    r->error = false;
	    if (expr.isUpdateExpression()) {
		r->result = "Update Expressions are not allowed";
		r->error = true;
	    }
	} catch (DbXml::XmlException const &xe) {
	    r->result = xe.what();
	    r->error = true;
	}
	return r;
    }

    void c_dbxml_version(int *major, int *minor, int *patch)
    {
	DbXml::dbxml_version(major, minor, patch);
    }

}
<commit_msg>bugfix in Open<commit_after>#include "c_dbxml.h"
#include <dbxml/DbXml.hpp>
#include <string>

#define ALIAS "c_dbxml"

extern "C" {

    struct c_dbxml_t {
	DbXml::XmlManager manager;
	DbXml::XmlUpdateContext context;
	DbXml::XmlContainer container;
	DbXml::XmlContainerConfig config;
	bool error;
	std::string filename;
	std::string errstring;
    };

    struct c_dbxml_result_t {
	std::string result;
	bool error;
    };

    struct c_dbxml_docs_t {
	DbXml::XmlDocument doc;
	DbXml::XmlValue value;
	DbXml::XmlResults it;
	DbXml::XmlQueryContext context;
	bool more;
	std::string name;
	std::string content;
	std::string match;
	bool error;
	std::string errstring;
    };

    struct c_dbxml_query_t {
	DbXml::XmlQueryContext context;
	DbXml::XmlQueryExpression expression;
	bool error;
	std::string errstring;
    };

    c_dbxml c_dbxml_open(char const *filename, int readwrite, int read)
    {
	c_dbxml db;

	db = new c_dbxml_t;
	db->filename = filename;

	for (int i = 0; i < 2; i++) {
	    /* if both: first attempt is read+write */
	    if (i == 0 && readwrite == 0) {
		continue;
	    }
	    if (i == 1 && read == 0) {
		continue;
	    }
	    try {
		db->context = db->manager.createUpdateContext();
		if (i == 0) {
		    db->config.setAllowCreate(true);
		    db->config.setMode(0666);
		} else {
		    db->config.setAllowCreate(false);
		    db->config.setReadOnly(true);
		}
		db->container = db->manager.openContainer(filename, db->config);
		db->error = false;
		if (!db->container.addAlias(ALIAS)) {
		    db->errstring = "Unable to add alias \"" ALIAS "\"";
		    db->error = true;
		}
	    } catch (DbXml::XmlException &xe) {
		db->errstring = xe.what();
		db->error = true;
	    }
	    if (db->error == false) {
		break;
	    }
	}

	return db;
    }

    void c_dbxml_free(c_dbxml db)
    {
	delete db;
    }

    int c_dbxml_error(c_dbxml db)
    {
	return db->error ? 1 : 0;
    }

    char const *c_dbxml_errstring(c_dbxml db)
    {
	return db->errstring.c_str();
    }

    void c_dbxml_result_free(c_dbxml_result r)
    {
	delete r;
    }

    int c_dbxml_result_error(c_dbxml_result r)
    {
	return r->error ? 1 : 0;
    }

    char const *c_dbxml_result_string(c_dbxml_result r)
    {
	return r->result.c_str();
    }

    c_dbxml_result c_dbxml_put_file(c_dbxml db, char const * filename, int replace)
    {
	c_dbxml_result r;
	r = new c_dbxml_result_t;

	if (replace) {
	    try {
		db->container.deleteDocument(filename, db->context);
	    } catch (DbXml::XmlException &xe) {
		;
	    }
	}
        try {
            DbXml::XmlInputStream *is = db->manager.createLocalFileInputStream(filename);
            db->container.putDocument(filename, is, db->context, DbXml::DBXML_WELL_FORMED_ONLY);
	    r->error = false;
        } catch (DbXml::XmlException &xe) {
	    r->result = xe.what();
	    r->error = true;
        }

	return r;
    }

    // replace if replace != 0
    c_dbxml_result c_dbxml_put_xml(c_dbxml db, char const *name, char const *data, int replace)
    {
	c_dbxml_result r;
	r = new c_dbxml_result_t;

	if (replace) {
	    try {
		db->container.deleteDocument(name, db->context);
	    } catch (DbXml::XmlException &xe) {
		;
	    }
	}

        try {
            db->container.putDocument(name, data, db->context);
	    r->error = false;
        } catch (DbXml::XmlException &xe) {
	    r->result = xe.what();
	    r->error = true;
        }
	return r;
    }

    // replace if replace != 0
    c_dbxml_result c_dbxml_merge(c_dbxml db, char const * dbxmlfile, int replace) {
	c_dbxml_result r;
	r = new c_dbxml_result_t;

	DbXml::XmlContainer input = db->manager.openContainer(dbxmlfile);
	DbXml::XmlDocument doc;
	DbXml::XmlResults it = input.getAllDocuments(DbXml::DBXML_LAZY_DOCS);
	while (it.next(doc)) {
	    if (replace) {
		try {
		    db->container.deleteDocument(doc.getName(), db->context);
		} catch (DbXml::XmlException &xe) {
		    ;
		}
	    }
	    try {
		db->container.putDocument(doc, db->context);
		r->error = false;
	    } catch (DbXml::XmlException &xe) {
		r->result = xe.what();
		r->error = true;
		return r;
	    }
	}
	return r;
    }

    c_dbxml_result c_dbxml_remove(c_dbxml db, char const * filename)
    {
	c_dbxml_result r;
	r = new c_dbxml_result_t;

	try {
	    db->container.deleteDocument(filename, db->context);
	    r->error = false;
        } catch (DbXml::XmlException &xe) {
	    r->result = xe.what();
	    r->error = true;
	}
	return r;
    }

    c_dbxml_result c_dbxml_get(c_dbxml db, char const * name)
    {
	c_dbxml_result r;
	r = new c_dbxml_result_t;
	try {
	    DbXml::XmlDocument doc = db->container.getDocument(name);
	    doc.getContent(r->result);
	    r->error = false;
	} catch (DbXml::XmlException &xe) {
	    r->result = xe.what();
	    r->error = true;
	}
	return r;
    }

    unsigned long long c_dbxml_size(c_dbxml db)
    {
	return (unsigned long long) db->container.getNumDocuments();
    }

    c_dbxml_docs c_dbxml_get_all(c_dbxml db)
    {
	c_dbxml_docs docs;
	docs = new c_dbxml_docs_t;
	docs->it = db->container.getAllDocuments(DbXml::DBXML_LAZY_DOCS);
	docs->more = true;
	docs->error = false;
	return docs;
    }

    c_dbxml_query c_dbxml_prepare_query(c_dbxml db, char const *query)
    {
	c_dbxml_query q;
	q = new c_dbxml_query_t;
	try {
	    q->context = db->manager.createQueryContext(DbXml::XmlQueryContext::LiveValues, DbXml::XmlQueryContext::Lazy);
	    q->context.setDefaultCollection(ALIAS);
	    q->expression = db->manager.prepare(std::string("collection('" ALIAS "')") + query, q->context);
	    q->error = false;
	    if (q->expression.isUpdateExpression()) {
		q->errstring = "Update Expressions are not allowed";
		q->error = true;
	    }
	} catch (DbXml::XmlException const &xe) {
	    q->errstring = xe.what();
	    q->error = true;
	}
	return q;
    }

    c_dbxml_docs c_dbxml_run_query(c_dbxml_query query)
    {
	c_dbxml_docs docs;
	docs = new c_dbxml_docs_t;
	docs->more = true;
	docs->context = query->context;
	try {
	    docs->it = query->expression.execute(docs->context,
						 DbXml::DBXML_LAZY_DOCS | DbXml::DBXML_WELL_FORMED_ONLY
						 );
	    docs->error = false;
	} catch (DbXml::XmlException const &xe) {
	    docs->more = false;
	    docs->errstring = xe.what();
	    docs->error = true;
	}

	return docs;
    }

    int c_dbxml_get_query_error(c_dbxml_docs docs)
    {
	return docs->error ? 1 : 0;
    }

    char const *c_dbxml_get_query_errstring(c_dbxml_docs docs)
    {
	return docs->errstring.c_str();
    }

    int c_dbxml_get_prepared_error(c_dbxml_query query)
    {
	return query->error ? 1 : 0;
    }

    char const *c_dbxml_get_prepared_errstring(c_dbxml_query query)
    {
	return query->errstring.c_str();
    }

    int c_dbxml_docs_next(c_dbxml_docs docs)
    {
	if (docs->more) {
	    try {
		docs->it.peek(docs->value);
		docs->more = docs->it.next(docs->doc);
	    } catch (DbXml::XmlException &xe) {
		docs->errstring = xe.what();
		docs->error = true;
		docs->more = false;
	    }
	    docs->name.clear();
	    docs->content.clear();
	    docs->match.clear();
	}
	return docs->more ? 1 : 0;
    }

    char const * c_dbxml_docs_name(c_dbxml_docs docs)
    {
	if (docs->more && ! docs->name.size())
	    docs->name = docs->doc.getName();

	return docs->name.c_str();
    }

    char const * c_dbxml_docs_content(c_dbxml_docs docs)
    {
	if (docs->more && ! docs->content.size())
	    docs->doc.getContent(docs->content);

	return docs->content.c_str();
    }

    char const * c_dbxml_docs_match(c_dbxml_docs docs)
    {
	if (docs->more && ! docs->match.size() && docs->value.isNode()) {
	    docs->match = docs->value.asString();
	}

	return docs->match.c_str();
    }

    void c_dbxml_docs_free(c_dbxml_docs docs)
    {
	delete docs;
    }

    void c_dbxml_query_free(c_dbxml_query query)
    {
	delete query;
    }

    void c_dbxml_cancel_query(c_dbxml_query query)
    {
	query->context.interruptQuery();
    }

    c_dbxml_result c_dbxml_check(char const *query)
    {
	c_dbxml_result r;
	r = new c_dbxml_result_t;
	try {
	    DbXml::XmlManager manager;
	    DbXml::XmlQueryContext context;
	    DbXml::XmlQueryExpression expr;
	    context = manager.createQueryContext(DbXml::XmlQueryContext::LiveValues, DbXml::XmlQueryContext::Lazy);
	    expr = manager.prepare(std::string(query), context);
	    r->error = false;
	    if (expr.isUpdateExpression()) {
		r->result = "Update Expressions are not allowed";
		r->error = true;
	    }
	} catch (DbXml::XmlException const &xe) {
	    r->result = xe.what();
	    r->error = true;
	}
	return r;
    }

    void c_dbxml_version(int *major, int *minor, int *patch)
    {
	DbXml::dbxml_version(major, minor, patch);
    }

}
<|endoftext|>


<commit_before><commit_msg>-Werror,-Wunused-const-variable<commit_after><|endoftext|>


<commit_before>/*-----------------------------------------------------------------------------
 This source file is part of Hopsan NG

 Copyright (c) 2011
    Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
    Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack

 This file is provided "as is", with no guarantee or warranty for the
 functionality or reliability of the contents. All contents in this file is
 the original work of the copyright holders at the Division of Fluid and
 Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
 redistributing any part of this file is prohibited without explicit
 permission from the copyright holders.
-----------------------------------------------------------------------------*/

//!
//! @file   AnimatedConnector.cpp
//! @author Robert Braun <robert.braun@liu.se
//! @date   2012-04-25
//!
//! @brief Contains a class for animated connectors
//!
//$Id$

#include <QDebug>
#include <QColor>
#include <QStyleOptionGraphicsItem>

#include "MainWindow.h"
#include "GraphicsView.h"
#include "AnimatedConnector.h"
#include "GUIObjects/AnimatedComponent.h"
#include "Widgets/ProjectTabWidget.h"
#include "GUIPort.h"
#include "GUIObjects/GUIModelObject.h"
#include "GUIConnectorAppearance.h"
#include "GUIConnector.h"
#include "GUIObjects/GUIContainerObject.h"

class UndoStack;

//! @brief Constructor for animated connector
//! @param [in] pConnector Pointer to the real connector the animation represents
//! @param [in] pAnimationWidget Pointer to animation widget where the connector is shown
AnimatedConnector::AnimatedConnector(Connector *pConnector, AnimationWidget *pAnimationWidget)
        : QGraphicsWidget()
{
    mpAnimationWidget = pAnimationWidget;
    mpConnector = pConnector;

    mpStartComponent = mpAnimationWidget->getAnimatedComponent(pConnector->getStartComponentName());
    mpEndComponent = mpAnimationWidget->getAnimatedComponent(pConnector->getEndComponentName());
    mStartPortName = pConnector->getStartPortName();
    mEndPortName = pConnector->getEndPortName();

    if(pConnector->getStartPort()->getNodeType() == "NodeHydraulic" && pConnector->getStartPort()->getPortType() != "READPORT" && pConnector->getEndPort()->getPortType() != "READPORT")
    {
        if(pConnector->getStartPort()->getPortType() == "POWERMULTIPORT")
        {
            int g = pConnector->getParentContainer()->getPlotDataPtr()->getLatestGeneration();
            QString componentName = pConnector->getEndPort()->getGuiModelObject()->getName();
            QString portName = pConnector->getEndPort()->getPortName();

            if(!pConnector->getParentContainer()->getPlotDataPtr()->isEmpty())
            {
                mvIntensityData = pConnector->getParentContainer()->getPlotDataPtr()->getPlotDataValues(g, componentName, portName, "Pressure");
                mvFlowData = pConnector->getParentContainer()->getPlotDataPtr()->getPlotDataValues(g, componentName, portName, "Flow");
            }
        }
        else
        {
            int g = pConnector->getParentContainer()->getPlotDataPtr()->getLatestGeneration();
            QString componentName = pConnector->getStartPort()->getGuiModelObject()->getName();
            QString portName = pConnector->getStartPort()->getPortName();

            if(!pConnector->getParentContainer()->getPlotDataPtr()->isEmpty())
            {
                mvIntensityData = pConnector->getParentContainer()->getPlotDataPtr()->getPlotDataValues(g, componentName, portName, "Pressure");
                mvFlowData = pConnector->getParentContainer()->getPlotDataPtr()->getPlotDataValues(g, componentName, portName, "Flow");
            }
        }

        if(mpConnector->getStartPort()->getPortType() == "POWERMULTIPORT")
        {
            mComponentName = mpConnector->getEndPort()->getGuiModelObject()->getName();
            mPortName = mpConnector->getEndPort()->getPortName();
        }
        else
        {
            mComponentName = mpConnector->getStartPort()->getGuiModelObject()->getName();
            mPortName = mpConnector->getStartPort()->getPortName();
        }

    }

    // Determine appearance
    mpConnectorAppearance = pConnector->mpConnectorAppearance;

    mPoints = pConnector->mPoints;

    // Create the lines
    for(int i=0; i < mPoints.size()-1; ++i)
    {
        AnimatedConnectorLine *pLine = new AnimatedConnectorLine(mapFromScene(mPoints[i]).x(), mapFromScene(mPoints[i]).y(),
                                                 mapFromScene(mPoints[i+1]).x(), mapFromScene(mPoints[i+1]).y(),
                                                 mpConnectorAppearance, this);

        QPen tempPen = pConnector->mpLines.at(i)->pen();
        mpLines.push_back(pLine);
        if(pConnector->mpLines.at(i)->mHasStartArrow)
        {
            pLine->addStartArrow();
        }
        if(pConnector->mpLines.at(i)->mHasEndArrow)
        {
            pLine->addEndArrow();
        }
        pLine->setPen(tempPen);
    }

    if(pConnector->getStartPort()->getGuiModelObject()->getTypeCQS() == "C")
    {
        mDirectionCorrection = 1;
    }
    else
    {
        mDirectionCorrection = -1;
    }
}

//! @brief Destructor for animated connector class
AnimatedConnector::~AnimatedConnector()
{
    delete mpConnectorAppearance;
}

//! @brief Updates the animated connector
void AnimatedConnector::updateAnimation()
{
    double max = mpAnimationWidget->mIntensityMaxMap.find("NodeHydraulic").value();
    double min = mpAnimationWidget->mIntensityMinMap.find("NodeHydraulic").value();

    QPen tempPen = mpLines.first()->pen();
    tempPen.setDashPattern(QVector<qreal>() << 1.5 << 3.5);

    double data, flowData;
    if(mpAnimationWidget->isRealTimeAnimation())    //Real-time animation
    {
        mpAnimationWidget->mpContainer->getCoreSystemAccessPtr()->getLastNodeData(mComponentName, mPortName, "Pressure", data);
        mpAnimationWidget->mpContainer->getCoreSystemAccessPtr()->getLastNodeData(mComponentName, mPortName, "Flow", flowData);
    }
    else if(!mvIntensityData.isEmpty())             //Replay animation
    {
        int index = mpAnimationWidget->getIndex();
        data = mvIntensityData[index];
        flowData = mvFlowData[index];
    }

    int red = std::min(255.0, 255*(data-min)/(0.8*max-min));
    int blue = 255-red;
    tempPen.setColor(QColor(red,0,blue));
    tempPen.setDashOffset(tempPen.dashOffset()+mDirectionCorrection*mpAnimationWidget->mFlowSpeedMap.find("NodeHydraulic").value()*flowData/* *fmod(mpAnimationWidget->getLastAnimationTime(),10.0)/10.0*/);

    for(int i=0; i<mpLines.size(); ++i)
    {
        mpLines[i]->setPen(tempPen);
    }

    QPointF startPos = mapFromItem(mpStartComponent->mpModelObject, mpStartComponent->getPortPos(mStartPortName));
    double x1 = startPos.x();
    double y1 = startPos.y();
    double x2 = mpLines.first()->line().x2();
    double y2 = mpLines.first()->line().y2();
    mpLines.first()->setLine(x1, y1, x2, y2);

    QPointF endPos = mapFromItem(mpEndComponent->mpModelObject, mpEndComponent->getPortPos(mEndPortName));
    x1 = mpLines.last()->line().x1();
    y1 = mpLines.last()->line().y1();
    x2 = endPos.x();
    y2 = endPos.y();
    mpLines.last()->setLine(x1, y1, x2, y2);
}

//------------------------------------------------------------------------------------------------------------------------//

//! @brief Constructor for animated connector lines
//! @param x1 X-coordinate of the start position of the line.
//! @param y1 Y-coordinate of the start position of the line.
//! @param x2 X-coordinate of the end position of the line.
//! @param y2 Y-coordinate of the end position of the line.
//! @param pConnApp Pointer to the connector appearance data, containing pens
//! @param *parent Pointer to the parent object (the animated connector)
AnimatedConnectorLine::AnimatedConnectorLine(qreal x1, qreal y1, qreal x2, qreal y2, ConnectorAppearance* pConnApp, AnimatedConnector *parent)
        : QGraphicsLineItem(x1,y1,x2,y2,parent)
{
    mpParentConnector = parent;
    setFlags(QGraphicsItem::ItemSendsGeometryChanges | QGraphicsItem::ItemUsesExtendedStyleOption);
    mpConnectorAppearance = pConnApp;
    this->setAcceptHoverEvents(true);
    this->mStartPos = QPointF(x1,y1);
    this->mEndPos = QPointF(x2,y2);
    mHasStartArrow = false;
    mHasEndArrow = false;
    mArrowSize = 8.0;
    mArrowAngle = 0.5;
}

//! @brief Destructor for animated connector lines
AnimatedConnectorLine::~AnimatedConnectorLine()
{
    clearArrows();
}

//! @brief Reimplementation of paint function. Removes the ugly dotted selection box.
void AnimatedConnectorLine::paint(QPainter *p, const QStyleOptionGraphicsItem *o, QWidget *w)
{
    QStyleOptionGraphicsItem *_o = const_cast<QStyleOptionGraphicsItem*>(o);
    _o->state &= ~QStyle::State_Selected;
    QGraphicsLineItem::paint(p,_o,w);
}

//! @brief Adds an arrow at the end of the line
//! @see addStartArrow()
void AnimatedConnectorLine::addEndArrow()
{
    clearArrows();

    qreal angle = atan2((this->mEndPos.y()-this->mStartPos.y()), (this->mEndPos.x()-this->mStartPos.x()));
    mArrowLine1 = new QGraphicsLineItem(this->mEndPos.x(),
                                        this->mEndPos.y(),
                                        this->mEndPos.x()-mArrowSize*cos(angle+mArrowAngle),
                                        this->mEndPos.y()-mArrowSize*sin(angle+mArrowAngle), this);
    mArrowLine2 = new QGraphicsLineItem(this->mEndPos.x(),
                                        this->mEndPos.y(),
                                        this->mEndPos.x()-mArrowSize*cos(angle-mArrowAngle),
                                        this->mEndPos.y()-mArrowSize*sin(angle-mArrowAngle), this);
    mArrowLine1->setPen(this->pen());
    mArrowLine2->setPen(this->pen());
    mHasEndArrow = true;
}

//! @brief Adds an arrow at the start of the line
//! @see addEndArrow()
void AnimatedConnectorLine::addStartArrow()
{
    clearArrows();

    qreal angle = atan2((this->mEndPos.y()-this->mStartPos.y()), (this->mEndPos.x()-this->mStartPos.x()));
    mArrowLine1 = new QGraphicsLineItem(this->mStartPos.x(),
                                        this->mStartPos.y(),
                                        this->mStartPos.x()+mArrowSize*cos(angle+mArrowAngle),
                                        this->mStartPos.y()+mArrowSize*sin(angle+mArrowAngle), this);
    mArrowLine2 = new QGraphicsLineItem(this->mStartPos.x(),
                                        this->mStartPos.y(),
                                        this->mStartPos.x()+mArrowSize*cos(angle-mArrowAngle),
                                        this->mStartPos.y()+mArrowSize*sin(angle-mArrowAngle), this);
    mArrowLine1->setPen(this->pen());
    mArrowLine2->setPen(this->pen());
    mHasStartArrow = true;
}

//! @brief Clears all arrows
void AnimatedConnectorLine::clearArrows()
{
    if (mHasStartArrow || mHasEndArrow)
    {
        delete mArrowLine1;
        delete mArrowLine2;
        mHasStartArrow = false;
        mHasEndArrow = false;
    }
}

//! @brief Reimplementation of setPen function, used to set the pen style for the arrow lines too
void AnimatedConnectorLine::setPen (const QPen &pen)
{
    QGraphicsLineItem::setPen(pen);
    if(mHasStartArrow | mHasEndArrow)       //Update arrow lines two, but ignore dashes
    {
        QPen tempPen = this->pen();
        tempPen = QPen(tempPen.color(), tempPen.width(), Qt::SolidLine);
        mArrowLine1->setPen(tempPen);
        mArrowLine2->setPen(tempPen);
    }
}
<commit_msg>Fixed crash when painting connectors in animation<commit_after>/*-----------------------------------------------------------------------------
 This source file is part of Hopsan NG

 Copyright (c) 2011
    Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
    Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack

 This file is provided "as is", with no guarantee or warranty for the
 functionality or reliability of the contents. All contents in this file is
 the original work of the copyright holders at the Division of Fluid and
 Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
 redistributing any part of this file is prohibited without explicit
 permission from the copyright holders.
-----------------------------------------------------------------------------*/

//!
//! @file   AnimatedConnector.cpp
//! @author Robert Braun <robert.braun@liu.se
//! @date   2012-04-25
//!
//! @brief Contains a class for animated connectors
//!
//$Id$

#include <QDebug>
#include <QColor>
#include <QStyleOptionGraphicsItem>

#include "MainWindow.h"
#include "GraphicsView.h"
#include "AnimatedConnector.h"
#include "GUIObjects/AnimatedComponent.h"
#include "Widgets/ProjectTabWidget.h"
#include "GUIPort.h"
#include "GUIObjects/GUIModelObject.h"
#include "GUIConnectorAppearance.h"
#include "GUIConnector.h"
#include "GUIObjects/GUIContainerObject.h"

class UndoStack;

//! @brief Constructor for animated connector
//! @param [in] pConnector Pointer to the real connector the animation represents
//! @param [in] pAnimationWidget Pointer to animation widget where the connector is shown
AnimatedConnector::AnimatedConnector(Connector *pConnector, AnimationWidget *pAnimationWidget)
        : QGraphicsWidget()
{
    mpAnimationWidget = pAnimationWidget;
    mpConnector = pConnector;

    mpStartComponent = mpAnimationWidget->getAnimatedComponent(pConnector->getStartComponentName());
    mpEndComponent = mpAnimationWidget->getAnimatedComponent(pConnector->getEndComponentName());
    mStartPortName = pConnector->getStartPortName();
    mEndPortName = pConnector->getEndPortName();

    if(pConnector->getStartPort()->getNodeType() == "NodeHydraulic" && pConnector->getStartPort()->getPortType() != "READPORT" && pConnector->getEndPort()->getPortType() != "READPORT")
    {
        if(pConnector->getStartPort()->getPortType() == "POWERMULTIPORT")
        {
            int g = pConnector->getParentContainer()->getPlotDataPtr()->getLatestGeneration();
            QString componentName = pConnector->getEndPort()->getGuiModelObject()->getName();
            QString portName = pConnector->getEndPort()->getPortName();

            if(!pConnector->getParentContainer()->getPlotDataPtr()->isEmpty())
            {
                mvIntensityData = pConnector->getParentContainer()->getPlotDataPtr()->getPlotDataValues(g, componentName, portName, "Pressure");
                mvFlowData = pConnector->getParentContainer()->getPlotDataPtr()->getPlotDataValues(g, componentName, portName, "Flow");
            }
        }
        else
        {
            int g = pConnector->getParentContainer()->getPlotDataPtr()->getLatestGeneration();
            QString componentName = pConnector->getStartPort()->getGuiModelObject()->getName();
            QString portName = pConnector->getStartPort()->getPortName();

            if(!pConnector->getParentContainer()->getPlotDataPtr()->isEmpty())
            {
                mvIntensityData = pConnector->getParentContainer()->getPlotDataPtr()->getPlotDataValues(g, componentName, portName, "Pressure");
                mvFlowData = pConnector->getParentContainer()->getPlotDataPtr()->getPlotDataValues(g, componentName, portName, "Flow");
            }
        }

        if(mpConnector->getStartPort()->getPortType() == "POWERMULTIPORT")
        {
            mComponentName = mpConnector->getEndPort()->getGuiModelObject()->getName();
            mPortName = mpConnector->getEndPort()->getPortName();
        }
        else
        {
            mComponentName = mpConnector->getStartPort()->getGuiModelObject()->getName();
            mPortName = mpConnector->getStartPort()->getPortName();
        }

    }

    // Determine appearance
    mpConnectorAppearance = pConnector->mpConnectorAppearance;

    mPoints = pConnector->mPoints;

    // Create the lines
    for(int i=0; i < mPoints.size()-1; ++i)
    {
        AnimatedConnectorLine *pLine = new AnimatedConnectorLine(mapFromScene(mPoints[i]).x(), mapFromScene(mPoints[i]).y(),
                                                 mapFromScene(mPoints[i+1]).x(), mapFromScene(mPoints[i+1]).y(),
                                                 mpConnectorAppearance, this);

        QPen tempPen = pConnector->mpLines.at(i)->pen();
        mpLines.push_back(pLine);
        if(pConnector->mpLines.at(i)->mHasStartArrow)
        {
            pLine->addStartArrow();
        }
        if(pConnector->mpLines.at(i)->mHasEndArrow)
        {
            pLine->addEndArrow();
        }
        pLine->setPen(tempPen);
    }

    if(pConnector->getStartPort()->getGuiModelObject()->getTypeCQS() == "C")
    {
        mDirectionCorrection = 1;
    }
    else
    {
        mDirectionCorrection = -1;
    }
}

//! @brief Destructor for animated connector class
AnimatedConnector::~AnimatedConnector()
{
    delete mpConnectorAppearance;
}

//! @brief Updates the animated connector
void AnimatedConnector::updateAnimation()
{
    if(mpConnector->getStartPort()->getNodeType() != "NodeHydraulic")
    {
        return;
    }

    double max = mpAnimationWidget->mIntensityMaxMap.find("NodeHydraulic").value();
    double min = mpAnimationWidget->mIntensityMinMap.find("NodeHydraulic").value();

    QPen tempPen = mpLines.first()->pen();
    tempPen.setDashPattern(QVector<qreal>() << 1.5 << 3.5);

    double data, flowData;
    if(mpAnimationWidget->isRealTimeAnimation())    //Real-time animation
    {
        mpAnimationWidget->mpContainer->getCoreSystemAccessPtr()->getLastNodeData(mComponentName, mPortName, "Pressure", data);
        mpAnimationWidget->mpContainer->getCoreSystemAccessPtr()->getLastNodeData(mComponentName, mPortName, "Flow", flowData);
    }
    else if(!mvIntensityData.isEmpty())             //Replay animation
    {
        int index = mpAnimationWidget->getIndex();
        data = mvIntensityData[index];
        flowData = mvFlowData[index];
    }

    int red = std::min(255.0, 255*(data-min)/(0.8*max-min));
    int blue = 255-red;
    tempPen.setColor(QColor(red,0,blue));
    tempPen.setDashOffset(tempPen.dashOffset()+mDirectionCorrection*mpAnimationWidget->mFlowSpeedMap.find("NodeHydraulic").value()*flowData/* *fmod(mpAnimationWidget->getLastAnimationTime(),10.0)/10.0*/);

    for(int i=0; i<mpLines.size(); ++i)
    {
        mpLines[i]->setPen(tempPen);
    }

    QPointF startPos = mapFromItem(mpStartComponent->mpModelObject, mpStartComponent->getPortPos(mStartPortName));
    double x1 = startPos.x();
    double y1 = startPos.y();
    double x2 = mpLines.first()->line().x2();
    double y2 = mpLines.first()->line().y2();
    mpLines.first()->setLine(x1, y1, x2, y2);

    QPointF endPos = mapFromItem(mpEndComponent->mpModelObject, mpEndComponent->getPortPos(mEndPortName));
    x1 = mpLines.last()->line().x1();
    y1 = mpLines.last()->line().y1();
    x2 = endPos.x();
    y2 = endPos.y();
    mpLines.last()->setLine(x1, y1, x2, y2);
}

//------------------------------------------------------------------------------------------------------------------------//

//! @brief Constructor for animated connector lines
//! @param x1 X-coordinate of the start position of the line.
//! @param y1 Y-coordinate of the start position of the line.
//! @param x2 X-coordinate of the end position of the line.
//! @param y2 Y-coordinate of the end position of the line.
//! @param pConnApp Pointer to the connector appearance data, containing pens
//! @param *parent Pointer to the parent object (the animated connector)
AnimatedConnectorLine::AnimatedConnectorLine(qreal x1, qreal y1, qreal x2, qreal y2, ConnectorAppearance* pConnApp, AnimatedConnector *parent)
        : QGraphicsLineItem(x1,y1,x2,y2,parent)
{
    mpParentConnector = parent;
    setFlags(QGraphicsItem::ItemSendsGeometryChanges | QGraphicsItem::ItemUsesExtendedStyleOption);
    mpConnectorAppearance = pConnApp;
    this->setAcceptHoverEvents(true);
    this->mStartPos = QPointF(x1,y1);
    this->mEndPos = QPointF(x2,y2);
    mHasStartArrow = false;
    mHasEndArrow = false;
    mArrowSize = 8.0;
    mArrowAngle = 0.5;
}

//! @brief Destructor for animated connector lines
AnimatedConnectorLine::~AnimatedConnectorLine()
{
    clearArrows();
}

//! @brief Reimplementation of paint function. Removes the ugly dotted selection box.
void AnimatedConnectorLine::paint(QPainter *p, const QStyleOptionGraphicsItem *o, QWidget *w)
{
    QStyleOptionGraphicsItem *_o = const_cast<QStyleOptionGraphicsItem*>(o);
    _o->state &= ~QStyle::State_Selected;
    QGraphicsLineItem::paint(p,_o,w);
}

//! @brief Adds an arrow at the end of the line
//! @see addStartArrow()
void AnimatedConnectorLine::addEndArrow()
{
    clearArrows();

    qreal angle = atan2((this->mEndPos.y()-this->mStartPos.y()), (this->mEndPos.x()-this->mStartPos.x()));
    mArrowLine1 = new QGraphicsLineItem(this->mEndPos.x(),
                                        this->mEndPos.y(),
                                        this->mEndPos.x()-mArrowSize*cos(angle+mArrowAngle),
                                        this->mEndPos.y()-mArrowSize*sin(angle+mArrowAngle), this);
    mArrowLine2 = new QGraphicsLineItem(this->mEndPos.x(),
                                        this->mEndPos.y(),
                                        this->mEndPos.x()-mArrowSize*cos(angle-mArrowAngle),
                                        this->mEndPos.y()-mArrowSize*sin(angle-mArrowAngle), this);
    mArrowLine1->setPen(this->pen());
    mArrowLine2->setPen(this->pen());
    mHasEndArrow = true;
}

//! @brief Adds an arrow at the start of the line
//! @see addEndArrow()
void AnimatedConnectorLine::addStartArrow()
{
    clearArrows();

    qreal angle = atan2((this->mEndPos.y()-this->mStartPos.y()), (this->mEndPos.x()-this->mStartPos.x()));
    mArrowLine1 = new QGraphicsLineItem(this->mStartPos.x(),
                                        this->mStartPos.y(),
                                        this->mStartPos.x()+mArrowSize*cos(angle+mArrowAngle),
                                        this->mStartPos.y()+mArrowSize*sin(angle+mArrowAngle), this);
    mArrowLine2 = new QGraphicsLineItem(this->mStartPos.x(),
                                        this->mStartPos.y(),
                                        this->mStartPos.x()+mArrowSize*cos(angle-mArrowAngle),
                                        this->mStartPos.y()+mArrowSize*sin(angle-mArrowAngle), this);
    mArrowLine1->setPen(this->pen());
    mArrowLine2->setPen(this->pen());
    mHasStartArrow = true;
}

//! @brief Clears all arrows
void AnimatedConnectorLine::clearArrows()
{
    if (mHasStartArrow || mHasEndArrow)
    {
        delete mArrowLine1;
        delete mArrowLine2;
        mHasStartArrow = false;
        mHasEndArrow = false;
    }
}

//! @brief Reimplementation of setPen function, used to set the pen style for the arrow lines too
void AnimatedConnectorLine::setPen (const QPen &pen)
{
    QGraphicsLineItem::setPen(pen);
    if(mHasStartArrow | mHasEndArrow)       //Update arrow lines two, but ignore dashes
    {
        QPen tempPen = this->pen();
        tempPen = QPen(tempPen.color(), tempPen.width(), Qt::SolidLine);
        mArrowLine1->setPen(tempPen);
        mArrowLine2->setPen(tempPen);
    }
}
<|endoftext|>