<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <tools/vcompat.hxx>

#include <vcl/graphictools.hxx>

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

SvtGraphicFill::Transform::Transform()
{
    matrix[0] = 1.0; matrix[1] = 0.0; matrix[2] = 0.0;
    matrix[3] = 0.0; matrix[4] = 1.0; matrix[5] = 0.0;
}

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

SvtGraphicStroke::SvtGraphicStroke() :
    maPath(),
    maStartArrow(),
    maEndArrow(),
    mfTransparency(),
    mfStrokeWidth(),
    maCapType(),
    maJoinType(),
    mfMiterLimit( 3.0 ),
    maDashArray()
{
}

SvtGraphicStroke::SvtGraphicStroke( const Polygon&      rPath,
                                    const PolyPolygon&  rStartArrow,
                                    const PolyPolygon&  rEndArrow,
                                    double              fTransparency,
                                    double              fStrokeWidth,
                                    CapType             aCap,
                                    JoinType            aJoin,
                                    double              fMiterLimit,
                                    const DashArray&    rDashArray  ) :
    maPath( rPath ),
    maStartArrow( rStartArrow ),
    maEndArrow( rEndArrow ),
    mfTransparency( fTransparency ),
    mfStrokeWidth( fStrokeWidth ),
    maCapType( aCap ),
    maJoinType( aJoin ),
    mfMiterLimit( fMiterLimit ),
    maDashArray( rDashArray )
{
}

void SvtGraphicStroke::getPath( Polygon& rPath ) const
{
    rPath = maPath;
}

void SvtGraphicStroke::getStartArrow( PolyPolygon& rPath ) const
{
    rPath = maStartArrow;
}

void SvtGraphicStroke::getEndArrow( PolyPolygon& rPath ) const
{
    rPath = maEndArrow;
}

double SvtGraphicStroke::getTransparency() const
{
    return mfTransparency;
}

double SvtGraphicStroke::getStrokeWidth() const
{
    return mfStrokeWidth;
}

SvtGraphicStroke::CapType SvtGraphicStroke::getCapType() const
{
    return maCapType;
}

SvtGraphicStroke::JoinType SvtGraphicStroke::getJoinType() const
{
    return maJoinType;
}

double SvtGraphicStroke::getMiterLimit() const
{
    return mfMiterLimit;
}

void SvtGraphicStroke::getDashArray( DashArray& rDashArray ) const
{
    rDashArray = maDashArray;
}

void SvtGraphicStroke::setPath( const Polygon& rPoly )
{
    maPath = rPoly;
}

void SvtGraphicStroke::scale( double fXScale, double fYScale )
{
    // Clearly scaling stroke-width for fat lines is rather a problem
    maPath.Scale( fXScale, fYScale );

    double fScale = sqrt (fabs (fXScale * fYScale) ); // clearly not ideal.
    fprintf( stderr, " HIT A SCALING ! by %g %g %g\n",
             (double) fXScale, (double) fYScale, (double) fScale );
    mfStrokeWidth *= fScale;
    mfMiterLimit *= fScale;

    maStartArrow.Scale( fXScale, fYScale );
    maEndArrow.Scale( fXScale, fYScale );
}

SvStream& operator<<( SvStream& rOStm, const SvtGraphicStroke& rClass )
{
    VersionCompat aCompat( rOStm, STREAM_WRITE, 1 );

    rClass.maPath.Write( rOStm );
    rClass.maStartArrow.Write( rOStm );
    rClass.maEndArrow.Write( rOStm );
    rOStm << rClass.mfTransparency;
    rOStm << rClass.mfStrokeWidth;
    sal_uInt16 nTmp = sal::static_int_cast<sal_uInt16>( rClass.maCapType );
    rOStm << nTmp;
    nTmp = sal::static_int_cast<sal_uInt16>( rClass.maJoinType );
    rOStm << nTmp;
    rOStm << rClass.mfMiterLimit;

    rOStm << static_cast<sal_uInt32>(rClass.maDashArray.size());
    size_t i;
    for(i=0; i<rClass.maDashArray.size(); ++i)
        rOStm << rClass.maDashArray[i];

    return rOStm;
}

SvStream& operator>>( SvStream& rIStm, SvtGraphicStroke& rClass )
{
    VersionCompat aCompat( rIStm, STREAM_READ );

    rClass.maPath.Read( rIStm );
    rClass.maStartArrow.Read( rIStm );
    rClass.maEndArrow.Read( rIStm );
    rIStm >> rClass.mfTransparency;
    rIStm >> rClass.mfStrokeWidth;
    sal_uInt16 nTmp;
    rIStm >> nTmp;
    rClass.maCapType = SvtGraphicStroke::CapType(nTmp);
    rIStm >> nTmp;
    rClass.maJoinType = SvtGraphicStroke::JoinType(nTmp);
    rIStm >> rClass.mfMiterLimit;

    sal_uInt32 nSize;
    rIStm >> nSize;
    rClass.maDashArray.resize(nSize);
    size_t i;
    for(i=0; i<rClass.maDashArray.size(); ++i)
        rIStm >> rClass.maDashArray[i];

    return rIStm;
}

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

SvtGraphicFill::SvtGraphicFill() :
    maPath(),
    maFillColor( COL_BLACK ),
    mfTransparency(),
    maFillRule(),
    maFillType(),
    maFillTransform(),
    maHatchType(),
    maHatchColor( COL_BLACK ),
    maGradientType(),
    maGradient1stColor( COL_BLACK ),
    maGradient2ndColor( COL_BLACK ),
    maGradientStepCount( gradientStepsInfinite ),
    maFillGraphic()
{
}

SvtGraphicFill::SvtGraphicFill( const PolyPolygon&  rPath,
                                Color               aFillColor,
                                double              fTransparency,
                                FillRule            aFillRule,
                                FillType            aFillType,
                                const Transform&    aFillTransform,
                                bool                bTiling,
                                HatchType           aHatchType,
                                Color               aHatchColor,
                                GradientType        aGradientType,
                                Color               aGradient1stColor,
                                Color               aGradient2ndColor,
                                sal_Int32           aGradientStepCount,
                                const Graphic&      aFillGraphic ) :
    maPath( rPath ),
    maFillColor( aFillColor ),
    mfTransparency( fTransparency ),
    maFillRule( aFillRule ),
    maFillType( aFillType ),
    maFillTransform( aFillTransform ),
    mbTiling( bTiling ),
    maHatchType( aHatchType ),
    maHatchColor( aHatchColor ),
    maGradientType( aGradientType ),
    maGradient1stColor( aGradient1stColor ),
    maGradient2ndColor( aGradient2ndColor ),
    maGradientStepCount( aGradientStepCount ),
    maFillGraphic( aFillGraphic )
{
}

void SvtGraphicFill::getPath( PolyPolygon& rPath ) const
{
    rPath = maPath;
}

Color SvtGraphicFill::getFillColor() const
{
    return maFillColor;
}

double SvtGraphicFill::getTransparency() const
{
    return mfTransparency;
}

SvtGraphicFill::FillRule SvtGraphicFill::getFillRule() const
{
    return maFillRule;
}

SvtGraphicFill::FillType SvtGraphicFill::getFillType() const
{
    return maFillType;
}

void SvtGraphicFill::getTransform( Transform& rTrans ) const
{
    rTrans = maFillTransform;
}

bool SvtGraphicFill::IsTiling() const
{
    return mbTiling;
}

bool SvtGraphicFill::isTiling() const
{
    return mbTiling;
}

SvtGraphicFill::GradientType SvtGraphicFill::getGradientType() const
{
    return maGradientType;
}

void SvtGraphicFill::getGraphic( Graphic& rGraphic ) const
{
    rGraphic = maFillGraphic;
}

void SvtGraphicFill::setPath( const PolyPolygon& rPath )
{
    maPath = rPath;
}

SvStream& operator<<( SvStream& rOStm, const SvtGraphicFill& rClass )
{
    VersionCompat aCompat( rOStm, STREAM_WRITE, 1 );

    rClass.maPath.Write( rOStm );
    rOStm << rClass.maFillColor;
    rOStm << rClass.mfTransparency;
    sal_uInt16 nTmp = sal::static_int_cast<sal_uInt16>( rClass.maFillRule );
    rOStm << nTmp;
    nTmp = sal::static_int_cast<sal_uInt16>( rClass.maFillType );
    rOStm << nTmp;
    int i;
    for(i=0; i<SvtGraphicFill::Transform::MatrixSize; ++i)
        rOStm << rClass.maFillTransform.matrix[i];
    nTmp = rClass.mbTiling;
    rOStm << nTmp;
    nTmp = sal::static_int_cast<sal_uInt16>( rClass.maHatchType );
    rOStm << nTmp;
    rOStm << rClass.maHatchColor;
    nTmp = sal::static_int_cast<sal_uInt16>( rClass.maGradientType );
    rOStm << nTmp;
    rOStm << rClass.maGradient1stColor;
    rOStm << rClass.maGradient2ndColor;
    rOStm << rClass.maGradientStepCount;
    rOStm << rClass.maFillGraphic;

    return rOStm;
}

SvStream& operator>>( SvStream& rIStm, SvtGraphicFill& rClass )
{
    VersionCompat aCompat( rIStm, STREAM_READ );

    rClass.maPath.Read( rIStm );
    rIStm >> rClass.maFillColor;
    rIStm >> rClass.mfTransparency;
    sal_uInt16 nTmp;
    rIStm >> nTmp;
    rClass.maFillRule = SvtGraphicFill::FillRule( nTmp );
    rIStm >> nTmp;
    rClass.maFillType = SvtGraphicFill::FillType( nTmp );
    int i;
    for(i=0; i<SvtGraphicFill::Transform::MatrixSize; ++i)
        rIStm >> rClass.maFillTransform.matrix[i];
    rIStm >> nTmp;
    rClass.mbTiling = nTmp;
    rIStm >> nTmp;
    rClass.maHatchType = SvtGraphicFill::HatchType( nTmp );
    rIStm >> rClass.maHatchColor;
    rIStm >> nTmp;
    rClass.maGradientType = SvtGraphicFill::GradientType( nTmp );
    rIStm >> rClass.maGradient1stColor;
    rIStm >> rClass.maGradient2ndColor;
    rIStm >> rClass.maGradientStepCount;
    rIStm >> rClass.maFillGraphic;

    return rIStm;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Fix error: use of undeclared identifier 'stderr'<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <stdio.h>

#include <tools/vcompat.hxx>

#include <vcl/graphictools.hxx>

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

SvtGraphicFill::Transform::Transform()
{
    matrix[0] = 1.0; matrix[1] = 0.0; matrix[2] = 0.0;
    matrix[3] = 0.0; matrix[4] = 1.0; matrix[5] = 0.0;
}

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

SvtGraphicStroke::SvtGraphicStroke() :
    maPath(),
    maStartArrow(),
    maEndArrow(),
    mfTransparency(),
    mfStrokeWidth(),
    maCapType(),
    maJoinType(),
    mfMiterLimit( 3.0 ),
    maDashArray()
{
}

SvtGraphicStroke::SvtGraphicStroke( const Polygon&      rPath,
                                    const PolyPolygon&  rStartArrow,
                                    const PolyPolygon&  rEndArrow,
                                    double              fTransparency,
                                    double              fStrokeWidth,
                                    CapType             aCap,
                                    JoinType            aJoin,
                                    double              fMiterLimit,
                                    const DashArray&    rDashArray  ) :
    maPath( rPath ),
    maStartArrow( rStartArrow ),
    maEndArrow( rEndArrow ),
    mfTransparency( fTransparency ),
    mfStrokeWidth( fStrokeWidth ),
    maCapType( aCap ),
    maJoinType( aJoin ),
    mfMiterLimit( fMiterLimit ),
    maDashArray( rDashArray )
{
}

void SvtGraphicStroke::getPath( Polygon& rPath ) const
{
    rPath = maPath;
}

void SvtGraphicStroke::getStartArrow( PolyPolygon& rPath ) const
{
    rPath = maStartArrow;
}

void SvtGraphicStroke::getEndArrow( PolyPolygon& rPath ) const
{
    rPath = maEndArrow;
}

double SvtGraphicStroke::getTransparency() const
{
    return mfTransparency;
}

double SvtGraphicStroke::getStrokeWidth() const
{
    return mfStrokeWidth;
}

SvtGraphicStroke::CapType SvtGraphicStroke::getCapType() const
{
    return maCapType;
}

SvtGraphicStroke::JoinType SvtGraphicStroke::getJoinType() const
{
    return maJoinType;
}

double SvtGraphicStroke::getMiterLimit() const
{
    return mfMiterLimit;
}

void SvtGraphicStroke::getDashArray( DashArray& rDashArray ) const
{
    rDashArray = maDashArray;
}

void SvtGraphicStroke::setPath( const Polygon& rPoly )
{
    maPath = rPoly;
}

void SvtGraphicStroke::scale( double fXScale, double fYScale )
{
    // Clearly scaling stroke-width for fat lines is rather a problem
    maPath.Scale( fXScale, fYScale );

    double fScale = sqrt (fabs (fXScale * fYScale) ); // clearly not ideal.
    fprintf( stderr, " HIT A SCALING ! by %g %g %g\n",
             (double) fXScale, (double) fYScale, (double) fScale );
    mfStrokeWidth *= fScale;
    mfMiterLimit *= fScale;

    maStartArrow.Scale( fXScale, fYScale );
    maEndArrow.Scale( fXScale, fYScale );
}

SvStream& operator<<( SvStream& rOStm, const SvtGraphicStroke& rClass )
{
    VersionCompat aCompat( rOStm, STREAM_WRITE, 1 );

    rClass.maPath.Write( rOStm );
    rClass.maStartArrow.Write( rOStm );
    rClass.maEndArrow.Write( rOStm );
    rOStm << rClass.mfTransparency;
    rOStm << rClass.mfStrokeWidth;
    sal_uInt16 nTmp = sal::static_int_cast<sal_uInt16>( rClass.maCapType );
    rOStm << nTmp;
    nTmp = sal::static_int_cast<sal_uInt16>( rClass.maJoinType );
    rOStm << nTmp;
    rOStm << rClass.mfMiterLimit;

    rOStm << static_cast<sal_uInt32>(rClass.maDashArray.size());
    size_t i;
    for(i=0; i<rClass.maDashArray.size(); ++i)
        rOStm << rClass.maDashArray[i];

    return rOStm;
}

SvStream& operator>>( SvStream& rIStm, SvtGraphicStroke& rClass )
{
    VersionCompat aCompat( rIStm, STREAM_READ );

    rClass.maPath.Read( rIStm );
    rClass.maStartArrow.Read( rIStm );
    rClass.maEndArrow.Read( rIStm );
    rIStm >> rClass.mfTransparency;
    rIStm >> rClass.mfStrokeWidth;
    sal_uInt16 nTmp;
    rIStm >> nTmp;
    rClass.maCapType = SvtGraphicStroke::CapType(nTmp);
    rIStm >> nTmp;
    rClass.maJoinType = SvtGraphicStroke::JoinType(nTmp);
    rIStm >> rClass.mfMiterLimit;

    sal_uInt32 nSize;
    rIStm >> nSize;
    rClass.maDashArray.resize(nSize);
    size_t i;
    for(i=0; i<rClass.maDashArray.size(); ++i)
        rIStm >> rClass.maDashArray[i];

    return rIStm;
}

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

SvtGraphicFill::SvtGraphicFill() :
    maPath(),
    maFillColor( COL_BLACK ),
    mfTransparency(),
    maFillRule(),
    maFillType(),
    maFillTransform(),
    maHatchType(),
    maHatchColor( COL_BLACK ),
    maGradientType(),
    maGradient1stColor( COL_BLACK ),
    maGradient2ndColor( COL_BLACK ),
    maGradientStepCount( gradientStepsInfinite ),
    maFillGraphic()
{
}

SvtGraphicFill::SvtGraphicFill( const PolyPolygon&  rPath,
                                Color               aFillColor,
                                double              fTransparency,
                                FillRule            aFillRule,
                                FillType            aFillType,
                                const Transform&    aFillTransform,
                                bool                bTiling,
                                HatchType           aHatchType,
                                Color               aHatchColor,
                                GradientType        aGradientType,
                                Color               aGradient1stColor,
                                Color               aGradient2ndColor,
                                sal_Int32           aGradientStepCount,
                                const Graphic&      aFillGraphic ) :
    maPath( rPath ),
    maFillColor( aFillColor ),
    mfTransparency( fTransparency ),
    maFillRule( aFillRule ),
    maFillType( aFillType ),
    maFillTransform( aFillTransform ),
    mbTiling( bTiling ),
    maHatchType( aHatchType ),
    maHatchColor( aHatchColor ),
    maGradientType( aGradientType ),
    maGradient1stColor( aGradient1stColor ),
    maGradient2ndColor( aGradient2ndColor ),
    maGradientStepCount( aGradientStepCount ),
    maFillGraphic( aFillGraphic )
{
}

void SvtGraphicFill::getPath( PolyPolygon& rPath ) const
{
    rPath = maPath;
}

Color SvtGraphicFill::getFillColor() const
{
    return maFillColor;
}

double SvtGraphicFill::getTransparency() const
{
    return mfTransparency;
}

SvtGraphicFill::FillRule SvtGraphicFill::getFillRule() const
{
    return maFillRule;
}

SvtGraphicFill::FillType SvtGraphicFill::getFillType() const
{
    return maFillType;
}

void SvtGraphicFill::getTransform( Transform& rTrans ) const
{
    rTrans = maFillTransform;
}

bool SvtGraphicFill::IsTiling() const
{
    return mbTiling;
}

bool SvtGraphicFill::isTiling() const
{
    return mbTiling;
}

SvtGraphicFill::GradientType SvtGraphicFill::getGradientType() const
{
    return maGradientType;
}

void SvtGraphicFill::getGraphic( Graphic& rGraphic ) const
{
    rGraphic = maFillGraphic;
}

void SvtGraphicFill::setPath( const PolyPolygon& rPath )
{
    maPath = rPath;
}

SvStream& operator<<( SvStream& rOStm, const SvtGraphicFill& rClass )
{
    VersionCompat aCompat( rOStm, STREAM_WRITE, 1 );

    rClass.maPath.Write( rOStm );
    rOStm << rClass.maFillColor;
    rOStm << rClass.mfTransparency;
    sal_uInt16 nTmp = sal::static_int_cast<sal_uInt16>( rClass.maFillRule );
    rOStm << nTmp;
    nTmp = sal::static_int_cast<sal_uInt16>( rClass.maFillType );
    rOStm << nTmp;
    int i;
    for(i=0; i<SvtGraphicFill::Transform::MatrixSize; ++i)
        rOStm << rClass.maFillTransform.matrix[i];
    nTmp = rClass.mbTiling;
    rOStm << nTmp;
    nTmp = sal::static_int_cast<sal_uInt16>( rClass.maHatchType );
    rOStm << nTmp;
    rOStm << rClass.maHatchColor;
    nTmp = sal::static_int_cast<sal_uInt16>( rClass.maGradientType );
    rOStm << nTmp;
    rOStm << rClass.maGradient1stColor;
    rOStm << rClass.maGradient2ndColor;
    rOStm << rClass.maGradientStepCount;
    rOStm << rClass.maFillGraphic;

    return rOStm;
}

SvStream& operator>>( SvStream& rIStm, SvtGraphicFill& rClass )
{
    VersionCompat aCompat( rIStm, STREAM_READ );

    rClass.maPath.Read( rIStm );
    rIStm >> rClass.maFillColor;
    rIStm >> rClass.mfTransparency;
    sal_uInt16 nTmp;
    rIStm >> nTmp;
    rClass.maFillRule = SvtGraphicFill::FillRule( nTmp );
    rIStm >> nTmp;
    rClass.maFillType = SvtGraphicFill::FillType( nTmp );
    int i;
    for(i=0; i<SvtGraphicFill::Transform::MatrixSize; ++i)
        rIStm >> rClass.maFillTransform.matrix[i];
    rIStm >> nTmp;
    rClass.mbTiling = nTmp;
    rIStm >> nTmp;
    rClass.maHatchType = SvtGraphicFill::HatchType( nTmp );
    rIStm >> rClass.maHatchColor;
    rIStm >> nTmp;
    rClass.maGradientType = SvtGraphicFill::GradientType( nTmp );
    rIStm >> rClass.maGradient1stColor;
    rIStm >> rClass.maGradient2ndColor;
    rIStm >> rClass.maGradientStepCount;
    rIStm >> rClass.maFillGraphic;

    return rIStm;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <tools/vcompat.hxx>

#include <vcl/graphictools.hxx>

SvtGraphicFill::Transform::Transform()
{
    matrix[0] = 1.0; matrix[1] = 0.0; matrix[2] = 0.0;
    matrix[3] = 0.0; matrix[4] = 1.0; matrix[5] = 0.0;
}

SvtGraphicStroke::SvtGraphicStroke() :
    maPath(),
    maStartArrow(),
    maEndArrow(),
    mfTransparency(),
    mfStrokeWidth(),
    maCapType(),
    maJoinType(),
    mfMiterLimit( 3.0 ),
    maDashArray()
{
}

SvtGraphicStroke::SvtGraphicStroke( const Polygon&      rPath,
                                    const PolyPolygon&  rStartArrow,
                                    const PolyPolygon&  rEndArrow,
                                    double              fTransparency,
                                    double              fStrokeWidth,
                                    CapType             aCap,
                                    JoinType            aJoin,
                                    double              fMiterLimit,
                                    const DashArray&    rDashArray  ) :
    maPath( rPath ),
    maStartArrow( rStartArrow ),
    maEndArrow( rEndArrow ),
    mfTransparency( fTransparency ),
    mfStrokeWidth( fStrokeWidth ),
    maCapType( aCap ),
    maJoinType( aJoin ),
    mfMiterLimit( fMiterLimit ),
    maDashArray( rDashArray )
{
}

void SvtGraphicStroke::getPath( Polygon& rPath ) const
{
    rPath = maPath;
}

void SvtGraphicStroke::getStartArrow( PolyPolygon& rPath ) const
{
    rPath = maStartArrow;
}

void SvtGraphicStroke::getEndArrow( PolyPolygon& rPath ) const
{
    rPath = maEndArrow;
}

double SvtGraphicStroke::getTransparency() const
{
    return mfTransparency;
}

double SvtGraphicStroke::getStrokeWidth() const
{
    return mfStrokeWidth;
}

SvtGraphicStroke::CapType SvtGraphicStroke::getCapType() const
{
    return maCapType;
}

SvtGraphicStroke::JoinType SvtGraphicStroke::getJoinType() const
{
    return maJoinType;
}

double SvtGraphicStroke::getMiterLimit() const
{
    return mfMiterLimit;
}

void SvtGraphicStroke::getDashArray( DashArray& rDashArray ) const
{
    rDashArray = maDashArray;
}

void SvtGraphicStroke::setPath( const Polygon& rPoly )
{
    maPath = rPoly;
}

void SvtGraphicStroke::setStartArrow( const PolyPolygon& rPoly )
{
    maStartArrow = rPoly;
}

void SvtGraphicStroke::setEndArrow( const PolyPolygon& rPoly )
{
    maEndArrow = rPoly;
}

void SvtGraphicStroke::scale( double fXScale, double fYScale )
{
    // Clearly scaling stroke-width for fat lines is rather a problem
    maPath.Scale( fXScale, fYScale );

    double fScale = sqrt (fabs (fXScale * fYScale) ); // clearly not ideal.
    mfStrokeWidth *= fScale;
    mfMiterLimit *= fScale;

    maStartArrow.Scale( fXScale, fYScale );
    maEndArrow.Scale( fXScale, fYScale );
}

SvStream& WriteSvtGraphicStroke( SvStream& rOStm, const SvtGraphicStroke& rClass )
{
    VersionCompat aCompat( rOStm, STREAM_WRITE, 1 );

    rClass.maPath.Write( rOStm );
    rClass.maStartArrow.Write( rOStm );
    rClass.maEndArrow.Write( rOStm );
    rOStm.WriteDouble( rClass.mfTransparency );
    rOStm.WriteDouble( rClass.mfStrokeWidth );
    sal_uInt16 nTmp = sal::static_int_cast<sal_uInt16>( rClass.maCapType );
    rOStm.WriteUInt16( nTmp );
    nTmp = sal::static_int_cast<sal_uInt16>( rClass.maJoinType );
    rOStm.WriteUInt16( nTmp );
    rOStm.WriteDouble( rClass.mfMiterLimit );

    rOStm.WriteUInt32( static_cast<sal_uInt32>(rClass.maDashArray.size()) );
    size_t i;
    for(i=0; i<rClass.maDashArray.size(); ++i)
        rOStm.WriteDouble( rClass.maDashArray[i] );

    return rOStm;
}

SvStream& ReadSvtGraphicStroke( SvStream& rIStm, SvtGraphicStroke& rClass )
{
    VersionCompat aCompat( rIStm, STREAM_READ );

    rClass.maPath.Read( rIStm );
    rClass.maStartArrow.Read( rIStm );
    rClass.maEndArrow.Read( rIStm );
    rIStm.ReadDouble( rClass.mfTransparency );
    rIStm.ReadDouble( rClass.mfStrokeWidth );
    sal_uInt16 nTmp;
    rIStm.ReadUInt16( nTmp );
    rClass.maCapType = SvtGraphicStroke::CapType(nTmp);
    rIStm.ReadUInt16( nTmp );
    rClass.maJoinType = SvtGraphicStroke::JoinType(nTmp);
    rIStm.ReadDouble( rClass.mfMiterLimit );

    sal_uInt32 nSize;
    rIStm.ReadUInt32( nSize );
    rClass.maDashArray.resize(nSize);
    size_t i;
    for(i=0; i<rClass.maDashArray.size(); ++i)
        rIStm.ReadDouble( rClass.maDashArray[i] );

    return rIStm;
}

SvtGraphicFill::SvtGraphicFill() :
    maPath(),
    maFillColor( COL_BLACK ),
    mfTransparency(),
    maFillRule(),
    maFillType(),
    maFillTransform(),
    maHatchType(),
    maHatchColor( COL_BLACK ),
    maGradientType(),
    maGradient1stColor( COL_BLACK ),
    maGradient2ndColor( COL_BLACK ),
    maGradientStepCount( gradientStepsInfinite ),
    maFillGraphic()
{
}

SvtGraphicFill::SvtGraphicFill( const PolyPolygon&  rPath,
                                Color               aFillColor,
                                double              fTransparency,
                                FillRule            aFillRule,
                                FillType            aFillType,
                                const Transform&    aFillTransform,
                                bool                bTiling,
                                HatchType           aHatchType,
                                Color               aHatchColor,
                                GradientType        aGradientType,
                                Color               aGradient1stColor,
                                Color               aGradient2ndColor,
                                sal_Int32           aGradientStepCount,
                                const Graphic&      aFillGraphic ) :
    maPath( rPath ),
    maFillColor( aFillColor ),
    mfTransparency( fTransparency ),
    maFillRule( aFillRule ),
    maFillType( aFillType ),
    maFillTransform( aFillTransform ),
    mbTiling( bTiling ),
    maHatchType( aHatchType ),
    maHatchColor( aHatchColor ),
    maGradientType( aGradientType ),
    maGradient1stColor( aGradient1stColor ),
    maGradient2ndColor( aGradient2ndColor ),
    maGradientStepCount( aGradientStepCount ),
    maFillGraphic( aFillGraphic )
{
}

void SvtGraphicFill::getPath( PolyPolygon& rPath ) const
{
    rPath = maPath;
}

Color SvtGraphicFill::getFillColor() const
{
    return maFillColor;
}

double SvtGraphicFill::getTransparency() const
{
    return mfTransparency;
}

SvtGraphicFill::FillRule SvtGraphicFill::getFillRule() const
{
    return maFillRule;
}

SvtGraphicFill::FillType SvtGraphicFill::getFillType() const
{
    return maFillType;
}

void SvtGraphicFill::getTransform( Transform& rTrans ) const
{
    rTrans = maFillTransform;
}

bool SvtGraphicFill::IsTiling() const
{
    return mbTiling;
}

bool SvtGraphicFill::isTiling() const
{
    return mbTiling;
}

SvtGraphicFill::GradientType SvtGraphicFill::getGradientType() const
{
    return maGradientType;
}

void SvtGraphicFill::getGraphic( Graphic& rGraphic ) const
{
    rGraphic = maFillGraphic;
}

void SvtGraphicFill::setPath( const PolyPolygon& rPath )
{
    maPath = rPath;
}

SvStream& WriteSvtGraphicFill( SvStream& rOStm, const SvtGraphicFill& rClass )
{
    VersionCompat aCompat( rOStm, STREAM_WRITE, 1 );

    rClass.maPath.Write( rOStm );
    WriteColor( rOStm, rClass.maFillColor );
    rOStm.WriteDouble( rClass.mfTransparency );
    sal_uInt16 nTmp = sal::static_int_cast<sal_uInt16>( rClass.maFillRule );
    rOStm.WriteUInt16( nTmp );
    nTmp = sal::static_int_cast<sal_uInt16>( rClass.maFillType );
    rOStm.WriteUInt16( nTmp );
    int i;
    for(i=0; i<SvtGraphicFill::Transform::MatrixSize; ++i)
        rOStm.WriteDouble( rClass.maFillTransform.matrix[i] );
    nTmp = sal_uInt16(rClass.mbTiling);
    rOStm.WriteUInt16( nTmp );
    nTmp = sal::static_int_cast<sal_uInt16>( rClass.maHatchType );
    rOStm.WriteUInt16( nTmp );
    WriteColor( rOStm, rClass.maHatchColor );
    nTmp = sal::static_int_cast<sal_uInt16>( rClass.maGradientType );
    rOStm.WriteUInt16( nTmp );
    WriteColor( rOStm, rClass.maGradient1stColor );
    WriteColor( rOStm, rClass.maGradient2ndColor );
    rOStm.WriteInt32( rClass.maGradientStepCount );
    WriteGraphic( rOStm, rClass.maFillGraphic );

    return rOStm;
}

SvStream& ReadSvtGraphicFill( SvStream& rIStm, SvtGraphicFill& rClass )
{
    VersionCompat aCompat( rIStm, STREAM_READ );

    rClass.maPath.Read( rIStm );
    ReadColor( rIStm, rClass.maFillColor );
    rIStm.ReadDouble( rClass.mfTransparency );
    sal_uInt16 nTmp;
    rIStm.ReadUInt16( nTmp );
    rClass.maFillRule = SvtGraphicFill::FillRule( nTmp );
    rIStm.ReadUInt16( nTmp );
    rClass.maFillType = SvtGraphicFill::FillType( nTmp );
    int i;
    for(i=0; i<SvtGraphicFill::Transform::MatrixSize; ++i)
        rIStm.ReadDouble( rClass.maFillTransform.matrix[i] );
    rIStm.ReadUInt16( nTmp );
    rClass.mbTiling = nTmp;
    rIStm.ReadUInt16( nTmp );
    rClass.maHatchType = SvtGraphicFill::HatchType( nTmp );
    ReadColor( rIStm, rClass.maHatchColor );
    rIStm.ReadUInt16( nTmp );
    rClass.maGradientType = SvtGraphicFill::GradientType( nTmp );
    ReadColor( rIStm, rClass.maGradient1stColor );
    ReadColor( rIStm, rClass.maGradient2ndColor );
    rIStm.ReadInt32( rClass.maGradientStepCount );
    ReadGraphic( rIStm, rClass.maFillGraphic );

    return rIStm;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#708597 Uninitialized scalar field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <tools/vcompat.hxx>

#include <vcl/graphictools.hxx>

SvtGraphicFill::Transform::Transform()
{
    matrix[0] = 1.0; matrix[1] = 0.0; matrix[2] = 0.0;
    matrix[3] = 0.0; matrix[4] = 1.0; matrix[5] = 0.0;
}

SvtGraphicStroke::SvtGraphicStroke() :
    maPath(),
    maStartArrow(),
    maEndArrow(),
    mfTransparency(),
    mfStrokeWidth(),
    maCapType(),
    maJoinType(),
    mfMiterLimit( 3.0 ),
    maDashArray()
{
}

SvtGraphicStroke::SvtGraphicStroke( const Polygon&      rPath,
                                    const PolyPolygon&  rStartArrow,
                                    const PolyPolygon&  rEndArrow,
                                    double              fTransparency,
                                    double              fStrokeWidth,
                                    CapType             aCap,
                                    JoinType            aJoin,
                                    double              fMiterLimit,
                                    const DashArray&    rDashArray  ) :
    maPath( rPath ),
    maStartArrow( rStartArrow ),
    maEndArrow( rEndArrow ),
    mfTransparency( fTransparency ),
    mfStrokeWidth( fStrokeWidth ),
    maCapType( aCap ),
    maJoinType( aJoin ),
    mfMiterLimit( fMiterLimit ),
    maDashArray( rDashArray )
{
}

void SvtGraphicStroke::getPath( Polygon& rPath ) const
{
    rPath = maPath;
}

void SvtGraphicStroke::getStartArrow( PolyPolygon& rPath ) const
{
    rPath = maStartArrow;
}

void SvtGraphicStroke::getEndArrow( PolyPolygon& rPath ) const
{
    rPath = maEndArrow;
}

double SvtGraphicStroke::getTransparency() const
{
    return mfTransparency;
}

double SvtGraphicStroke::getStrokeWidth() const
{
    return mfStrokeWidth;
}

SvtGraphicStroke::CapType SvtGraphicStroke::getCapType() const
{
    return maCapType;
}

SvtGraphicStroke::JoinType SvtGraphicStroke::getJoinType() const
{
    return maJoinType;
}

double SvtGraphicStroke::getMiterLimit() const
{
    return mfMiterLimit;
}

void SvtGraphicStroke::getDashArray( DashArray& rDashArray ) const
{
    rDashArray = maDashArray;
}

void SvtGraphicStroke::setPath( const Polygon& rPoly )
{
    maPath = rPoly;
}

void SvtGraphicStroke::setStartArrow( const PolyPolygon& rPoly )
{
    maStartArrow = rPoly;
}

void SvtGraphicStroke::setEndArrow( const PolyPolygon& rPoly )
{
    maEndArrow = rPoly;
}

void SvtGraphicStroke::scale( double fXScale, double fYScale )
{
    // Clearly scaling stroke-width for fat lines is rather a problem
    maPath.Scale( fXScale, fYScale );

    double fScale = sqrt (fabs (fXScale * fYScale) ); // clearly not ideal.
    mfStrokeWidth *= fScale;
    mfMiterLimit *= fScale;

    maStartArrow.Scale( fXScale, fYScale );
    maEndArrow.Scale( fXScale, fYScale );
}

SvStream& WriteSvtGraphicStroke( SvStream& rOStm, const SvtGraphicStroke& rClass )
{
    VersionCompat aCompat( rOStm, STREAM_WRITE, 1 );

    rClass.maPath.Write( rOStm );
    rClass.maStartArrow.Write( rOStm );
    rClass.maEndArrow.Write( rOStm );
    rOStm.WriteDouble( rClass.mfTransparency );
    rOStm.WriteDouble( rClass.mfStrokeWidth );
    sal_uInt16 nTmp = sal::static_int_cast<sal_uInt16>( rClass.maCapType );
    rOStm.WriteUInt16( nTmp );
    nTmp = sal::static_int_cast<sal_uInt16>( rClass.maJoinType );
    rOStm.WriteUInt16( nTmp );
    rOStm.WriteDouble( rClass.mfMiterLimit );

    rOStm.WriteUInt32( static_cast<sal_uInt32>(rClass.maDashArray.size()) );
    size_t i;
    for(i=0; i<rClass.maDashArray.size(); ++i)
        rOStm.WriteDouble( rClass.maDashArray[i] );

    return rOStm;
}

SvStream& ReadSvtGraphicStroke( SvStream& rIStm, SvtGraphicStroke& rClass )
{
    VersionCompat aCompat( rIStm, STREAM_READ );

    rClass.maPath.Read( rIStm );
    rClass.maStartArrow.Read( rIStm );
    rClass.maEndArrow.Read( rIStm );
    rIStm.ReadDouble( rClass.mfTransparency );
    rIStm.ReadDouble( rClass.mfStrokeWidth );
    sal_uInt16 nTmp;
    rIStm.ReadUInt16( nTmp );
    rClass.maCapType = SvtGraphicStroke::CapType(nTmp);
    rIStm.ReadUInt16( nTmp );
    rClass.maJoinType = SvtGraphicStroke::JoinType(nTmp);
    rIStm.ReadDouble( rClass.mfMiterLimit );

    sal_uInt32 nSize;
    rIStm.ReadUInt32( nSize );
    rClass.maDashArray.resize(nSize);
    size_t i;
    for(i=0; i<rClass.maDashArray.size(); ++i)
        rIStm.ReadDouble( rClass.maDashArray[i] );

    return rIStm;
}

SvtGraphicFill::SvtGraphicFill() :
    maPath(),
    maFillColor( COL_BLACK ),
    mfTransparency(),
    maFillRule(),
    maFillType(),
    maFillTransform(),
    mbTiling( false ),
    maHatchType(),
    maHatchColor( COL_BLACK ),
    maGradientType(),
    maGradient1stColor( COL_BLACK ),
    maGradient2ndColor( COL_BLACK ),
    maGradientStepCount( gradientStepsInfinite ),
    maFillGraphic()
{
}

SvtGraphicFill::SvtGraphicFill( const PolyPolygon&  rPath,
                                Color               aFillColor,
                                double              fTransparency,
                                FillRule            aFillRule,
                                FillType            aFillType,
                                const Transform&    aFillTransform,
                                bool                bTiling,
                                HatchType           aHatchType,
                                Color               aHatchColor,
                                GradientType        aGradientType,
                                Color               aGradient1stColor,
                                Color               aGradient2ndColor,
                                sal_Int32           aGradientStepCount,
                                const Graphic&      aFillGraphic ) :
    maPath( rPath ),
    maFillColor( aFillColor ),
    mfTransparency( fTransparency ),
    maFillRule( aFillRule ),
    maFillType( aFillType ),
    maFillTransform( aFillTransform ),
    mbTiling( bTiling ),
    maHatchType( aHatchType ),
    maHatchColor( aHatchColor ),
    maGradientType( aGradientType ),
    maGradient1stColor( aGradient1stColor ),
    maGradient2ndColor( aGradient2ndColor ),
    maGradientStepCount( aGradientStepCount ),
    maFillGraphic( aFillGraphic )
{
}

void SvtGraphicFill::getPath( PolyPolygon& rPath ) const
{
    rPath = maPath;
}

Color SvtGraphicFill::getFillColor() const
{
    return maFillColor;
}

double SvtGraphicFill::getTransparency() const
{
    return mfTransparency;
}

SvtGraphicFill::FillRule SvtGraphicFill::getFillRule() const
{
    return maFillRule;
}

SvtGraphicFill::FillType SvtGraphicFill::getFillType() const
{
    return maFillType;
}

void SvtGraphicFill::getTransform( Transform& rTrans ) const
{
    rTrans = maFillTransform;
}

bool SvtGraphicFill::IsTiling() const
{
    return mbTiling;
}

bool SvtGraphicFill::isTiling() const
{
    return mbTiling;
}

SvtGraphicFill::GradientType SvtGraphicFill::getGradientType() const
{
    return maGradientType;
}

void SvtGraphicFill::getGraphic( Graphic& rGraphic ) const
{
    rGraphic = maFillGraphic;
}

void SvtGraphicFill::setPath( const PolyPolygon& rPath )
{
    maPath = rPath;
}

SvStream& WriteSvtGraphicFill( SvStream& rOStm, const SvtGraphicFill& rClass )
{
    VersionCompat aCompat( rOStm, STREAM_WRITE, 1 );

    rClass.maPath.Write( rOStm );
    WriteColor( rOStm, rClass.maFillColor );
    rOStm.WriteDouble( rClass.mfTransparency );
    sal_uInt16 nTmp = sal::static_int_cast<sal_uInt16>( rClass.maFillRule );
    rOStm.WriteUInt16( nTmp );
    nTmp = sal::static_int_cast<sal_uInt16>( rClass.maFillType );
    rOStm.WriteUInt16( nTmp );
    int i;
    for(i=0; i<SvtGraphicFill::Transform::MatrixSize; ++i)
        rOStm.WriteDouble( rClass.maFillTransform.matrix[i] );
    nTmp = sal_uInt16(rClass.mbTiling);
    rOStm.WriteUInt16( nTmp );
    nTmp = sal::static_int_cast<sal_uInt16>( rClass.maHatchType );
    rOStm.WriteUInt16( nTmp );
    WriteColor( rOStm, rClass.maHatchColor );
    nTmp = sal::static_int_cast<sal_uInt16>( rClass.maGradientType );
    rOStm.WriteUInt16( nTmp );
    WriteColor( rOStm, rClass.maGradient1stColor );
    WriteColor( rOStm, rClass.maGradient2ndColor );
    rOStm.WriteInt32( rClass.maGradientStepCount );
    WriteGraphic( rOStm, rClass.maFillGraphic );

    return rOStm;
}

SvStream& ReadSvtGraphicFill( SvStream& rIStm, SvtGraphicFill& rClass )
{
    VersionCompat aCompat( rIStm, STREAM_READ );

    rClass.maPath.Read( rIStm );
    ReadColor( rIStm, rClass.maFillColor );
    rIStm.ReadDouble( rClass.mfTransparency );
    sal_uInt16 nTmp;
    rIStm.ReadUInt16( nTmp );
    rClass.maFillRule = SvtGraphicFill::FillRule( nTmp );
    rIStm.ReadUInt16( nTmp );
    rClass.maFillType = SvtGraphicFill::FillType( nTmp );
    int i;
    for(i=0; i<SvtGraphicFill::Transform::MatrixSize; ++i)
        rIStm.ReadDouble( rClass.maFillTransform.matrix[i] );
    rIStm.ReadUInt16( nTmp );
    rClass.mbTiling = nTmp;
    rIStm.ReadUInt16( nTmp );
    rClass.maHatchType = SvtGraphicFill::HatchType( nTmp );
    ReadColor( rIStm, rClass.maHatchColor );
    rIStm.ReadUInt16( nTmp );
    rClass.maGradientType = SvtGraphicFill::GradientType( nTmp );
    ReadColor( rIStm, rClass.maGradient1stColor );
    ReadColor( rIStm, rClass.maGradient2ndColor );
    rIStm.ReadInt32( rClass.maGradientStepCount );
    ReadGraphic( rIStm, rClass.maFillGraphic );

    return rIStm;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include "General.h"
#include <string>
#include "tools/StringManipulation.h"
#include <math.h>

using namespace std;
General::General(Bot* x) {
	bot = x;
}

General::~General() {

}

int General::pickStartingRegions(std::vector<int> pickfrom) {

	//this function still needs implemented, we currently are just given random
	//areas to begin with

	return pickfrom.front();
}

std::vector<Move> General::generateNonAttack() {

	/*this function will take as input a region that has no enemy or neutral
	 * neighbors around it and calculates the best route to send the troops as
	 * to reinforce and/or start attacking
	 * this will bing an optimized path problem aka Dijkstra's algorithm
	 *
	 */

	return std::vector<Move>();
}

void General::getDeployment() {

	//creates a variable to store which super region I have troops in that has the least amount of regions left to take
	int lowestSuper = 100;

	//variables for the calculations
	Region regionAddingTo;
	int temp;

	//get all regions owned by me
	vector<Region> myRegions= bot->getOwnedRegions();

	//loop through all of my regions and find the region that is in the super region that is easiest to take
	for(Region r: myRegions)
	{
		//get the amount of regions left in the super region
		temp = bot->regionsLeftInSuper(bot->superRegions[r.superRegion]);

		//if there are less regions to take in this super region, add make this region the one we add troops to
		if(temp < lowestSuper && temp != 0)
		{
			lowestSuper = temp;
			regionAddingTo = r;
		}

	}

	//add all of the troops to the region that is in the easiest super region to take
	std::cout << bot->botName << " place_armies " << regionAddingTo.id << " " << bot->armiesLeft
	<< std::endl;

	//update the number of armies left in the bot class
	bot->addArmies(regionAddingTo.id, bot->armiesLeft);

	return;
}

void General::calculateTurn() {
	//This call attack and deffense and then combines the moves?
	vector<Move> moves = generateAttacks();

	sendToEngineAttack(moves);
}

vector<Move> General::generateAttacks()
{
	int counter = 0;

	vector<Move> moves;

	// Get adjacent regions depending on owner.
	vector<Region> myRegions = bot->getRegionsOwnedBy(ME);

	// Look at potential enemy attacks
	for (Region n : myRegions) {

		if(n.armies == 1)
			continue;

		vector<Region> Nb = bot->otherNbInSuperRegion(n);

		if(Nb.empty())
		{
			Nb = bot->getOtherNeighbors(n);

			if(Nb.empty())
			{
				//Nb = bot->getNeighbors(ME, n);

				Move transfer = calculateTransfer(n);

				//Need to push moves this way to prevent seg fault
				moves.push_back(Move());

				//you'll push to moves this way. Every other way seems to seg fault
				moves[counter].to = transfer.from;
				moves[counter].from = transfer.to;
				moves[counter++].armies = transfer.armies;
			}
		}

		Region attackingRegion;

		for(Region r: Nb)
		{
			if(r.owner == ENEMY)
			{
				//you'll push to moves this way. Every other way seems to seg fault
				if(n.armies >= r.armies * 2)
				{
					//Need to push moves this way to prevent seg fault
					moves.push_back(Move());

					moves[counter].to = r;
					moves[counter].from = n;
					moves[counter++].armies = r.armies * 2;
					n.setArmies(n.armies - r.armies * 2);
				}
			}
		}

		for(Region r: Nb)
		{
			if(r.owner == NEUTRAL)
			{
				//you'll push to moves this way. Every other way seems to seg fault
				if(n.armies >= r.armies * 2)
				{
					//Need to push moves this way to prevent seg fault
					moves.push_back(Move());

					moves[counter].to = r;
					moves[counter].from = n;
					moves[counter++].armies = r.armies * 2;
					n.setArmies(n.armies - r.armies * 2);
				}
			}
		}
	}

	return moves;
}

Move General::calculateTransfer(Region place)
{
	vector<Region> MyNb = bot->getNeighbors(ME, place);

	Move transfer;

	transfer.from = place;

	transfer.to = MyNb[rand() % MyNb.size()];

	transfer.armies = transfer.from.getArmies() - 1;

	return transfer;
}

void General::sendToEngineAttack(vector<Move> attacks)
{
	if(attacks.empty())
		return;

	std::vector<std::string> attackMoves;
	std::stringstream attackMove;

	for(Move m: attacks)
	{

			attackMove << bot->botName << " attack/transfer " << m.from.id << " " << m.to.id
				<< " " << m.armies << ",";

		attackMoves.push_back(attackMove.str());

	}
	std::cout << string::join(attackMoves) << std::endl;
}

<commit_msg>Short fix<commit_after>#include "General.h"
#include <string>
#include "tools/StringManipulation.h"
#include <math.h>

using namespace std;
General::General(Bot* x) {
	bot = x;
}

General::~General() {

}

int General::pickStartingRegions(std::vector<int> pickfrom) {

	//this function still needs implemented, we currently are just given random
	//areas to begin with

	return pickfrom.front();
}

std::vector<Move> General::generateNonAttack() {

	/*this function will take as input a region that has no enemy or neutral
	 * neighbors around it and calculates the best route to send the troops as
	 * to reinforce and/or start attacking
	 * this will bing an optimized path problem aka Dijkstra's algorithm
	 *
	 */

	return std::vector<Move>();
}

void General::getDeployment() {

	//creates a variable to store which super region I have troops in that has the least amount of regions left to take
	int lowestSuper = 100;

	//variables for the calculations
	Region regionAddingTo;
	int temp;

	//get all regions owned by me
	vector<Region> myRegions= bot->getOwnedRegions();

	//loop through all of my regions and find the region that is in the super region that is easiest to take
	for(Region r: myRegions)
	{
		//get the amount of regions left in the super region
		temp = bot->regionsLeftInSuper(bot->superRegions[r.superRegion]);

		//if there are less regions to take in this super region, add make this region the one we add troops to
		if(temp < lowestSuper && temp != 0)
		{
			lowestSuper = temp;
			regionAddingTo = r;
		}

	}

	//add all of the troops to the region that is in the easiest super region to take
	std::cout << bot->botName << " place_armies " << regionAddingTo.id << " " << bot->armiesLeft
	<< std::endl;

	//update the number of armies left in the bot class
	bot->addArmies(regionAddingTo.id, bot->armiesLeft);

	return;
}

void General::calculateTurn() {
	//This call attack and deffense and then combines the moves?
	vector<Move> moves = generateAttacks();

	sendToEngineAttack(moves);
}

vector<Move> General::generateAttacks()
{
	int counter = 0;

	vector<Move> moves;

	// Get adjacent regions depending on owner.
	vector<Region> myRegions = bot->getRegionsOwnedBy(ME);

	// Look at potential enemy attacks
	for (Region n : myRegions) {

		if(n.armies == 1)
			continue;

		vector<Region> Nb = bot->otherNbInSuperRegion(n);

		if(Nb.empty())
		{
			Nb = bot->getOtherNeighbors(n);

			if(Nb.empty())
			{
				//Nb = bot->getNeighbors(ME, n);

				Move transfer = calculateTransfer(n);

				//Need to push moves this way to prevent seg fault
				moves.push_back(Move());

				//you'll push to moves this way. Every other way seems to seg fault
				moves[counter].to = transfer.from;
				moves[counter].from = transfer.to;
				moves[counter++].armies = transfer.armies;
			}
		}

		for(Region r: Nb)
		{
			if(r.owner == ENEMY)
			{
				//you'll push to moves this way. Every other way seems to seg fault
				if(n.armies >= r.armies * 2)
				{
					//Need to push moves this way to prevent seg fault
					moves.push_back(Move());

					moves[counter].to = r;
					moves[counter].from = n;
					moves[counter++].armies = r.armies * 2;
					n.setArmies(n.armies - r.armies * 2);
				}
			}
		}

		for(Region r: Nb)
		{
			if(r.owner == NEUTRAL)
			{
				//you'll push to moves this way. Every other way seems to seg fault
				if(n.armies >= r.armies * 2)
				{
					//Need to push moves this way to prevent seg fault
					moves.push_back(Move());

					moves[counter].to = r;
					moves[counter].from = n;
					moves[counter++].armies = r.armies * 2;
					n.setArmies(n.armies - r.armies * 2);
				}
			}
		}
	}

	return moves;
}

Move General::calculateTransfer(Region place)
{
	vector<Region> MyNb = bot->getNeighbors(ME, place);

	Move transfer;

	transfer.from = place;

	transfer.to = MyNb[rand() % MyNb.size()];

	transfer.armies = transfer.from.getArmies() - 1;

	return transfer;
}

void General::sendToEngineAttack(vector<Move> attacks)
{
	if(attacks.empty())
		return;

	std::vector<std::string> attackMoves;
	std::stringstream attackMove;

	for(Move m: attacks)
	{

			attackMove << bot->botName << " attack/transfer " << m.from.id << " " << m.to.id
				<< " " << m.armies << ",";

		attackMoves.push_back(attackMove.str());

	}
	std::cout << string::join(attackMoves) << std::endl;
}

<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-2011, Willow Garage, Inc.
 *  Copyright (c) 2012-, Open Perception, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the copyright holder(s) nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id: octree_pointcloud_voxelcentroid.hpp 6459 2012-07-18 07:50:37Z dpb $
 */

#ifndef PCL_OCTREE_VOXELCENTROID_HPP
#define PCL_OCTREE_VOXELCENTROID_HPP

#include <pcl/octree/octree_pointcloud_voxelcentroid.h>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename BranchT> bool
pcl::octree::OctreePointCloudVoxelCentroid<PointT, LeafT, BranchT>::getVoxelCentroidAtPoint (
    const PointT& point_arg, PointT& voxel_centroid_arg) const
{

  OctreeKey key;
  LeafNode* leaf = 0;

  // generate key
  genOctreeKeyforPoint (point_arg, key);

  leaf = this->findLeaf (key);

  if (leaf)
  {
    LeafT* container = leaf;
    container->getCentroid (voxel_centroid_arg);
  }

  return (leaf!=0);
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename BranchT> size_t
pcl::octree::OctreePointCloudVoxelCentroid<PointT, LeafT, BranchT>::getVoxelCentroids (
    typename OctreePointCloud<PointT, LeafT, BranchT>::AlignedPointTVector &voxel_centroid_list_arg) const
{

  OctreeKey newKey;

  // reset output vector
  voxel_centroid_list_arg.clear ();
  voxel_centroid_list_arg.reserve (this->leafCount_);

  getVoxelCentroidsRecursive (this->rootNode_, newKey, voxel_centroid_list_arg );

  // return size of centroid vector
  return (voxel_centroid_list_arg.size ());
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename BranchT> void
pcl::octree::OctreePointCloudVoxelCentroid<PointT, LeafT, BranchT>::getVoxelCentroidsRecursive (
    const BranchNode* branch_arg, OctreeKey& key_arg,
    typename OctreePointCloud<PointT, LeafT, BranchT>::AlignedPointTVector &voxel_centroid_list_arg) const
{

  // child iterator
  unsigned char childIdx;

  // iterate over all children
  for (childIdx = 0; childIdx < 8; childIdx++)
  {

    // if child exist
    if (branch_arg->hasChild(childIdx))
    {
      // add current branch voxel to key
      key_arg.pushBranch(childIdx);

      const OctreeNode *childNode = branch_arg->getChildPtr(childIdx);

      switch (childNode->getNodeType ())
      {
        case BRANCH_NODE:
        {
          // recursively proceed with indexed child branch
          getVoxelCentroidsRecursive (static_cast<const BranchNode*> (childNode), key_arg, voxel_centroid_list_arg);
          break;
        }
        case LEAF_NODE:
        {
          const LeafT* container = static_cast<const LeafNode*> (childNode);

          PointXYZ newCentroid;
          container->getCentroid(newCentroid);

          voxel_centroid_list_arg.push_back(newCentroid);
          break;
        }
        default:
          break;
       }

      // pop current branch voxel from key
      key_arg.popBranch();
    }
  }

}

#define PCL_INSTANTIATE_OctreePointCloudVoxelCentroid(T) template class PCL_EXPORTS pcl::octree::OctreePointCloudVoxelCentroid<T>;

#endif

<commit_msg>fixed compilation error<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-2011, Willow Garage, Inc.
 *  Copyright (c) 2012-, Open Perception, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the copyright holder(s) nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id: octree_pointcloud_voxelcentroid.hpp 6459 2012-07-18 07:50:37Z dpb $
 */

#ifndef PCL_OCTREE_VOXELCENTROID_HPP
#define PCL_OCTREE_VOXELCENTROID_HPP

#include <pcl/octree/octree_pointcloud_voxelcentroid.h>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename BranchT> bool
pcl::octree::OctreePointCloudVoxelCentroid<PointT, LeafT, BranchT>::getVoxelCentroidAtPoint (
    const PointT& point_arg, PointT& voxel_centroid_arg) const
{
  OctreeKey key;
  LeafNode* leaf = 0;

  // generate key
  genOctreeKeyforPoint (point_arg, key);

  leaf = this->findLeaf (key);

  if (leaf)
  {
    LeafT* container = leaf;
    container->getCentroid (voxel_centroid_arg);
  }

  return (leaf != 0);
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename BranchT> size_t
pcl::octree::OctreePointCloudVoxelCentroid<PointT, LeafT, BranchT>::getVoxelCentroids (
    typename OctreePointCloud<PointT, LeafT, BranchT>::AlignedPointTVector &voxel_centroid_list_arg) const
{
  OctreeKey new_key;

  // reset output vector
  voxel_centroid_list_arg.clear ();
  voxel_centroid_list_arg.reserve (this->leafCount_);

  getVoxelCentroidsRecursive (this->rootNode_, new_key, voxel_centroid_list_arg );

  // return size of centroid vector
  return (voxel_centroid_list_arg.size ());
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename BranchT> void
pcl::octree::OctreePointCloudVoxelCentroid<PointT, LeafT, BranchT>::getVoxelCentroidsRecursive (
    const BranchNode* branch_arg, OctreeKey& key_arg,
    typename OctreePointCloud<PointT, LeafT, BranchT>::AlignedPointTVector &voxel_centroid_list_arg) const
{
  // child iterator
  unsigned char child_idx;

  // iterate over all children
  for (child_idx = 0; child_idx < 8; child_idx++)
  {
    // if child exist
    if (branch_arg->hasChild (child_idx))
    {
      // add current branch voxel to key
      key_arg.pushBranch (child_idx);

      const OctreeNode *childNode = branch_arg->getChildPtr (child_idx);

      switch (childNode->getNodeType ())
      {
        case BRANCH_NODE:
        {
          // recursively proceed with indexed child branch
          getVoxelCentroidsRecursive (static_cast<const BranchNode*> (childNode), key_arg, voxel_centroid_list_arg);
          break;
        }
        case LEAF_NODE:
        {
          const LeafT* container = static_cast<const LeafNode*> (childNode);

          PointT new_centroid;
          container->getCentroid (new_centroid);

          voxel_centroid_list_arg.push_back (new_centroid);
          break;
        }
        default:
          break;
       }

      // pop current branch voxel from key
      key_arg.popBranch ();
    }
  }
}

#define PCL_INSTANTIATE_OctreePointCloudVoxelCentroid(T) template class PCL_EXPORTS pcl::octree::OctreePointCloudVoxelCentroid<T>;

#endif

<|endoftext|>


<commit_before>#ifndef VEXCL_BACKEND_OPENCL_FILTER_HPP
#define VEXCL_BACKEND_OPENCL_FILTER_HPP

/*
The MIT License

Copyright (c) 2012-2016 Denis Demidov <dennis.demidov@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/**
 * \file   vexcl/backend/opencl/filter.hpp
 * \author Denis Demidov <dennis.demidov@gmail.com>
 * \brief  Device filters for OpenCL backend.
 */

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <functional>
#include <cstdlib>

#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/filesystem.hpp>
#include <boost/config.hpp>
#include <boost/version.hpp>

#include <vexcl/backend/opencl/defines.hpp>
#include <CL/cl2.hpp>

namespace vex {

/// Device filters.
namespace Filter {

    /// Selects devices whose vendor name match given value.
    struct Vendor {
        explicit Vendor(std::string name) : vendor(std::move(name)) {}

        bool operator()(const cl::Device &d) const {
            return d.getInfo<CL_DEVICE_VENDOR>().find(vendor) != std::string::npos;
        }

        private:
            std::string vendor;
    };

    /// Selects devices whose platform name match given value.
    struct Platform {
        explicit Platform(std::string name) : platform(std::move(name)) {}

        bool operator()(const cl::Device &d) const {
            return cl::Platform(d.getInfo<CL_DEVICE_PLATFORM>()).getInfo<CL_PLATFORM_NAME>().find(platform) != std::string::npos;
        }

        private:
            std::string platform;
    };

    /// Selects devices whose names match given value.
    struct Name {
        explicit Name(std::string name) : devname(std::move(name)) {}

        bool operator()(const cl::Device &d) const {
            return d.getInfo<CL_DEVICE_NAME>().find(devname) != std::string::npos;
        }

        private:
            std::string devname;
    };

    /// Selects devices by type.
    struct Type {
        explicit Type(cl_device_type t)    : type(t)              {}
        explicit Type(const std::string t) : type(device_type(t)) {}

        bool operator()(const cl::Device &d) const {
            return 0 != (d.getInfo<CL_DEVICE_TYPE>() & type);
        }

        private:
            cl_device_type type;

            static cl_device_type device_type(const std::string &t) {
                if (t.find("CPU") != std::string::npos)
                    return CL_DEVICE_TYPE_CPU;

                if (t.find("GPU") != std::string::npos)
                    return CL_DEVICE_TYPE_GPU;

                if (t.find("ACCELERATOR") != std::string::npos)
                    return CL_DEVICE_TYPE_ACCELERATOR;

                return CL_DEVICE_TYPE_ALL;
            }
    };

    /// Selects CPU devices
    const Type CPU        (CL_DEVICE_TYPE_CPU);
    /// Selects GPU devices
    const Type GPU        (CL_DEVICE_TYPE_GPU);
    /// Selects accelerator devices
    const Type Accelerator(CL_DEVICE_TYPE_ACCELERATOR);

    /// \cond INTERNAL
    struct DoublePrecisionFilter {
        bool operator()(const cl::Device &d) const {
            std::string ext = d.getInfo<CL_DEVICE_EXTENSIONS>();
            return (
                    ext.find("cl_khr_fp64") != std::string::npos ||
                    ext.find("cl_amd_fp64") != std::string::npos
                   );
        }
    };
    /// \endcond

    /// Selects devices supporting double precision.
    const DoublePrecisionFilter DoublePrecision = {};

    /// Selects devices providing given OpenCL extensions.
    struct Extension {
        std::string extension;

        Extension(std::string ext) : extension(std::move(ext)) {}

        bool operator()(const cl::Device& d) const {
            std::string ext = d.getInfo<CL_DEVICE_EXTENSIONS>();
            return ext.find(extension) != std::string::npos;
        }
    };

    /// Selects devices supporting OpenGL Sharing Extension
    const Extension GLSharing(
    #if defined(__APPLE__)
        "cl_apple_gl_sharing"
    #else
        "cl_khr_gl_sharing"
    #endif
    );

    /// Selects device by OpenCL version.
    struct CLVersion {
        std::tuple<int, int> min_version;

        CLVersion(int major, int minor) : min_version(major, minor) {}

        bool operator()(const cl::Device &d) const {
            // version contains OpenCL n.m
            //                  0123456789
            std::string version = d.getInfo<CL_DRIVER_VERSION>();

            return min_version <= std::make_tuple(version[7]-'0', version[9]-'0');
        }
    };

    /// List of device filters based on environment variables.
    inline std::vector< std::function<bool(const cl::Device&)> >
    backend_env_filters()
    {
        std::vector< std::function<bool(const cl::Device&)> > filter;

#ifdef _MSC_VER
#  pragma warning(push)
#  pragma warning(disable: 4996)
#endif
        const char *platform  = getenv("OCL_PLATFORM");
        const char *vendor    = getenv("OCL_VENDOR");
        const char *name      = getenv("OCL_DEVICE");
        const char *devtype   = getenv("OCL_TYPE");
        const char *extension = getenv("OCL_EXTENSION");
#ifdef _MSC_VER
#  pragma warning(pop)
#endif

        if (platform)  filter.push_back(Platform(platform));
        if (vendor)    filter.push_back(Vendor(vendor));
        if (name)      filter.push_back(Name(name));
        if (devtype)   filter.push_back(Type(devtype));
        if (extension) filter.push_back(Extension(extension));

        return filter;
    }

    /// \internal Exclusive access to selected devices.
    class ExclusiveFilter {
        private:
            std::function<bool(const cl::Device&)> filter;

            static std::map<cl_device_id, std::string> get_uids() {
                std::map<cl_device_id, std::string> uids;

                std::vector<cl::Platform> platform;
                cl::Platform::get(&platform);

#ifdef _MSC_VER
#  pragma warning(push)
#  pragma warning(disable: 4996)
#endif
                const char *lock_dir = getenv("VEXCL_LOCK_DIR");
#ifdef _MSC_VER
#  pragma warning(pop)
#endif

                for(size_t p_id = 0; p_id < platform.size(); p_id++) {
                    std::vector<cl::Device> device;

                    platform[p_id].getDevices(CL_DEVICE_TYPE_ALL, &device);

                    for(size_t d_id = 0; d_id < device.size(); d_id++) {
                        std::ostringstream id;
#ifdef WIN32
#  ifdef _MSC_VER
#    pragma warning(push)
#    pragma warning(disable: 4996)
#  endif
                        id << (lock_dir ? lock_dir : getenv("TEMP")) << "\\";
#  ifdef _MSC_VER
#    pragma warning(pop)
#  endif
#else
                        id << (lock_dir ? lock_dir : "/tmp") << "/";
#endif
                        id << "vexcl_device_" << p_id << "_" << d_id << ".lock";

                        uids[device[d_id]()] = id.str();
                    }
                }

                return uids;
            }

            struct locker {
                locker(std::string fname) : file(fname)
                {
                    if (!file.is_open() || file.fail()) {
                        std::cerr
                            << "WARNING: failed to open file \"" << fname << "\"\n"
                            << "  Check that target directory is exists and is writable.\n"
                            << "  Exclusive mode is off.\n"
                            << std::endl;
                    } else {
                        flock.reset(new boost::interprocess::file_lock(fname.c_str()));
#if BOOST_VERSION >= 105000
                        // In case we created the lock file,
                        // lets make it writable by others:
                        try {
                            boost::filesystem::permissions(fname, boost::filesystem::all_all);
                        } catch (const boost::filesystem::filesystem_error&) {
                            (void)0;
                        }
#endif
                    }
                }

                bool try_lock() {
                    if (flock) {
                        // Try and lock the file related to compute device.
                        // If the file is locked already, it could mean two
                        // things:
                        // 1. Somebody locked the file, and uses the device.
                        // 2. Somebody locked the file, and is in process of
                        //    checking the device. If device is not good (for
                        //    them) they will release the lock in a few
                        //    moments.
                        // To process case 2 correctly, we use timed_lock().

                        return flock->timed_lock(
                                boost::posix_time::microsec_clock::universal_time() +
                                boost::posix_time::milliseconds(100)
                                );
                    } else return true;
                }

                std::ofstream file;
                std::unique_ptr<boost::interprocess::file_lock> flock;
            };
        public:
            template <class Filter>
            ExclusiveFilter(Filter&& filter)
                : filter(std::forward<Filter>(filter)) {}

            bool operator()(const cl::Device &d) const {
                static std::map<cl_device_id, std::string> dev_uids = get_uids();
                static /*thread_local*/ std::vector<std::unique_ptr<locker>> locks;

                std::unique_ptr<locker> lck(new locker(dev_uids[d()]));

                if (lck->try_lock() && filter(d)) {
                    locks.push_back(std::move(lck));
                    return true;
                }

                return false;
            }

    };

    /// Allows exclusive access to compute devices across several processes.
    /**
     * Returns devices that pass through provided device filter and are not
     * locked.
     *
     * \param filter Compute device filter
     *
     * \note Depends on boost::interprocess library.
     *
     * lock files are created in directory specified in VEXCL_LOCK_DIR
     * environment variable. If the variable does not exist, /tmp is
     * used on Linux and %TMPDIR% on Windows. The lock directory should exist
     * and be writable by the running user.
     */
    template <class Filter>
    ExclusiveFilter Exclusive(Filter&& filter) {
        return ExclusiveFilter(std::forward<Filter>(filter));
    }

} // namespace Filter
} // namespace vex

#endif
<commit_msg>Fix a bug in vex::Filter::CLVersion for OpenCL backend<commit_after>#ifndef VEXCL_BACKEND_OPENCL_FILTER_HPP
#define VEXCL_BACKEND_OPENCL_FILTER_HPP

/*
The MIT License

Copyright (c) 2012-2016 Denis Demidov <dennis.demidov@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/**
 * \file   vexcl/backend/opencl/filter.hpp
 * \author Denis Demidov <dennis.demidov@gmail.com>
 * \brief  Device filters for OpenCL backend.
 */

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <functional>
#include <cstdlib>

#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/filesystem.hpp>
#include <boost/config.hpp>
#include <boost/version.hpp>

#include <vexcl/backend/opencl/defines.hpp>
#include <CL/cl2.hpp>

namespace vex {

/// Device filters.
namespace Filter {

    /// Selects devices whose vendor name match given value.
    struct Vendor {
        explicit Vendor(std::string name) : vendor(std::move(name)) {}

        bool operator()(const cl::Device &d) const {
            return d.getInfo<CL_DEVICE_VENDOR>().find(vendor) != std::string::npos;
        }

        private:
            std::string vendor;
    };

    /// Selects devices whose platform name match given value.
    struct Platform {
        explicit Platform(std::string name) : platform(std::move(name)) {}

        bool operator()(const cl::Device &d) const {
            return cl::Platform(d.getInfo<CL_DEVICE_PLATFORM>()).getInfo<CL_PLATFORM_NAME>().find(platform) != std::string::npos;
        }

        private:
            std::string platform;
    };

    /// Selects devices whose names match given value.
    struct Name {
        explicit Name(std::string name) : devname(std::move(name)) {}

        bool operator()(const cl::Device &d) const {
            return d.getInfo<CL_DEVICE_NAME>().find(devname) != std::string::npos;
        }

        private:
            std::string devname;
    };

    /// Selects devices by type.
    struct Type {
        explicit Type(cl_device_type t)    : type(t)              {}
        explicit Type(const std::string t) : type(device_type(t)) {}

        bool operator()(const cl::Device &d) const {
            return 0 != (d.getInfo<CL_DEVICE_TYPE>() & type);
        }

        private:
            cl_device_type type;

            static cl_device_type device_type(const std::string &t) {
                if (t.find("CPU") != std::string::npos)
                    return CL_DEVICE_TYPE_CPU;

                if (t.find("GPU") != std::string::npos)
                    return CL_DEVICE_TYPE_GPU;

                if (t.find("ACCELERATOR") != std::string::npos)
                    return CL_DEVICE_TYPE_ACCELERATOR;

                return CL_DEVICE_TYPE_ALL;
            }
    };

    /// Selects CPU devices
    const Type CPU        (CL_DEVICE_TYPE_CPU);
    /// Selects GPU devices
    const Type GPU        (CL_DEVICE_TYPE_GPU);
    /// Selects accelerator devices
    const Type Accelerator(CL_DEVICE_TYPE_ACCELERATOR);

    /// \cond INTERNAL
    struct DoublePrecisionFilter {
        bool operator()(const cl::Device &d) const {
            std::string ext = d.getInfo<CL_DEVICE_EXTENSIONS>();
            return (
                    ext.find("cl_khr_fp64") != std::string::npos ||
                    ext.find("cl_amd_fp64") != std::string::npos
                   );
        }
    };
    /// \endcond

    /// Selects devices supporting double precision.
    const DoublePrecisionFilter DoublePrecision = {};

    /// Selects devices providing given OpenCL extensions.
    struct Extension {
        std::string extension;

        Extension(std::string ext) : extension(std::move(ext)) {}

        bool operator()(const cl::Device& d) const {
            std::string ext = d.getInfo<CL_DEVICE_EXTENSIONS>();
            return ext.find(extension) != std::string::npos;
        }
    };

    /// Selects devices supporting OpenGL Sharing Extension
    const Extension GLSharing(
    #if defined(__APPLE__)
        "cl_apple_gl_sharing"
    #else
        "cl_khr_gl_sharing"
    #endif
    );

    /// Selects device by OpenCL version.
    struct CLVersion {
        std::tuple<int, int> min_version;

        CLVersion(int major, int minor) : min_version(major, minor) {}

        bool operator()(const cl::Device &d) const {
            // version contains OpenCL n.m
            //                  0123456789
            std::string version = d.getInfo<CL_DEVICE_VERSION>();

            return min_version <= std::make_tuple(version[7]-'0', version[9]-'0');
        }
    };

    /// List of device filters based on environment variables.
    inline std::vector< std::function<bool(const cl::Device&)> >
    backend_env_filters()
    {
        std::vector< std::function<bool(const cl::Device&)> > filter;

#ifdef _MSC_VER
#  pragma warning(push)
#  pragma warning(disable: 4996)
#endif
        const char *platform  = getenv("OCL_PLATFORM");
        const char *vendor    = getenv("OCL_VENDOR");
        const char *name      = getenv("OCL_DEVICE");
        const char *devtype   = getenv("OCL_TYPE");
        const char *extension = getenv("OCL_EXTENSION");
#ifdef _MSC_VER
#  pragma warning(pop)
#endif

        if (platform)  filter.push_back(Platform(platform));
        if (vendor)    filter.push_back(Vendor(vendor));
        if (name)      filter.push_back(Name(name));
        if (devtype)   filter.push_back(Type(devtype));
        if (extension) filter.push_back(Extension(extension));

        return filter;
    }

    /// \internal Exclusive access to selected devices.
    class ExclusiveFilter {
        private:
            std::function<bool(const cl::Device&)> filter;

            static std::map<cl_device_id, std::string> get_uids() {
                std::map<cl_device_id, std::string> uids;

                std::vector<cl::Platform> platform;
                cl::Platform::get(&platform);

#ifdef _MSC_VER
#  pragma warning(push)
#  pragma warning(disable: 4996)
#endif
                const char *lock_dir = getenv("VEXCL_LOCK_DIR");
#ifdef _MSC_VER
#  pragma warning(pop)
#endif

                for(size_t p_id = 0; p_id < platform.size(); p_id++) {
                    std::vector<cl::Device> device;

                    platform[p_id].getDevices(CL_DEVICE_TYPE_ALL, &device);

                    for(size_t d_id = 0; d_id < device.size(); d_id++) {
                        std::ostringstream id;
#ifdef WIN32
#  ifdef _MSC_VER
#    pragma warning(push)
#    pragma warning(disable: 4996)
#  endif
                        id << (lock_dir ? lock_dir : getenv("TEMP")) << "\\";
#  ifdef _MSC_VER
#    pragma warning(pop)
#  endif
#else
                        id << (lock_dir ? lock_dir : "/tmp") << "/";
#endif
                        id << "vexcl_device_" << p_id << "_" << d_id << ".lock";

                        uids[device[d_id]()] = id.str();
                    }
                }

                return uids;
            }

            struct locker {
                locker(std::string fname) : file(fname)
                {
                    if (!file.is_open() || file.fail()) {
                        std::cerr
                            << "WARNING: failed to open file \"" << fname << "\"\n"
                            << "  Check that target directory is exists and is writable.\n"
                            << "  Exclusive mode is off.\n"
                            << std::endl;
                    } else {
                        flock.reset(new boost::interprocess::file_lock(fname.c_str()));
#if BOOST_VERSION >= 105000
                        // In case we created the lock file,
                        // lets make it writable by others:
                        try {
                            boost::filesystem::permissions(fname, boost::filesystem::all_all);
                        } catch (const boost::filesystem::filesystem_error&) {
                            (void)0;
                        }
#endif
                    }
                }

                bool try_lock() {
                    if (flock) {
                        // Try and lock the file related to compute device.
                        // If the file is locked already, it could mean two
                        // things:
                        // 1. Somebody locked the file, and uses the device.
                        // 2. Somebody locked the file, and is in process of
                        //    checking the device. If device is not good (for
                        //    them) they will release the lock in a few
                        //    moments.
                        // To process case 2 correctly, we use timed_lock().

                        return flock->timed_lock(
                                boost::posix_time::microsec_clock::universal_time() +
                                boost::posix_time::milliseconds(100)
                                );
                    } else return true;
                }

                std::ofstream file;
                std::unique_ptr<boost::interprocess::file_lock> flock;
            };
        public:
            template <class Filter>
            ExclusiveFilter(Filter&& filter)
                : filter(std::forward<Filter>(filter)) {}

            bool operator()(const cl::Device &d) const {
                static std::map<cl_device_id, std::string> dev_uids = get_uids();
                static /*thread_local*/ std::vector<std::unique_ptr<locker>> locks;

                std::unique_ptr<locker> lck(new locker(dev_uids[d()]));

                if (lck->try_lock() && filter(d)) {
                    locks.push_back(std::move(lck));
                    return true;
                }

                return false;
            }

    };

    /// Allows exclusive access to compute devices across several processes.
    /**
     * Returns devices that pass through provided device filter and are not
     * locked.
     *
     * \param filter Compute device filter
     *
     * \note Depends on boost::interprocess library.
     *
     * lock files are created in directory specified in VEXCL_LOCK_DIR
     * environment variable. If the variable does not exist, /tmp is
     * used on Linux and %TMPDIR% on Windows. The lock directory should exist
     * and be writable by the running user.
     */
    template <class Filter>
    ExclusiveFilter Exclusive(Filter&& filter) {
        return ExclusiveFilter(std::forward<Filter>(filter));
    }

} // namespace Filter
} // namespace vex

#endif
<|endoftext|>


<commit_before>#ifndef VIENNAGRID_STORAGE_INSERTER_HPP
#define VIENNAGRID_STORAGE_INSERTER_HPP

//#include "viennagrid/storage/reference.hpp"
#include "viennagrid/storage/container_collection.hpp"
#include "viennagrid/storage/container_collection_element.hpp"

namespace viennagrid
{
    namespace storage
    {

        template<typename container_collection_type>
        class inserter_base_t
        {
        public:
            inserter_base_t(container_collection_type & _collection) : collection(_collection) {}

        protected:
            container_collection_type & collection;
        };

        template<typename container_collection_type, typename id_generator_type__>
        class physical_inserter_t
        {
        public:
            typedef container_collection_type physical_container_collection_type;
            typedef id_generator_type__ id_generator_type;

            physical_inserter_t(container_collection_type & _collection, id_generator_type id_generator__) : collection(_collection), id_generator(id_generator__) {}

            template<typename value_type, typename inserter_type>
            std::pair<
                typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_type,
                bool
            >
                    physical_insert( value_type element, inserter_type & inserter )
            {
                typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::iterator iterator;
                typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type container_type;
                typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_tag hook_tag;
                typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_type hook_type;

                if ( !viennagrid::storage::container_collection::get< value_type >( collection ).is_present( element ) )
                    viennagrid::storage::id::set_id(element, id_generator( viennameta::tag<value_type>() ) );

                std::pair<hook_type, bool> ret = viennagrid::storage::container_collection::get< value_type >( collection ).insert( element );

                viennagrid::storage::container_collection_element::insert_callback(*ret.first, ret.second, inserter);

                inserter.hook_insert( ret.first, viennameta::tag<value_type>() );

                return ret;
            }

            template<typename hook_type, typename value_type>
            void hook_insert( hook_type ref, viennameta::tag<value_type> )
            {}

            template<typename value_type>
            std::pair<
                typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_type,
                bool
            >
                operator()( const value_type & element )
            {
                return physical_insert( element, *this );
            }

        private:
            container_collection_type & collection;
            id_generator_type id_generator;
        };

        template<typename view_collection_type, typename dependend_inserter_type>
        class recursive_inserter_t : public dependend_inserter_type
        {
        public:
            typedef dependend_inserter_type base;

            recursive_inserter_t(view_collection_type & _collection, const dependend_inserter_type & dependend_inserter) :
                dependend_inserter_type(dependend_inserter), view_collection(_collection) {}

            template<typename hook_type, typename value_type>
            void hook_insert( hook_type ref, viennameta::tag<value_type> )
            {
                viennagrid::storage::container_collection::hook_or_ignore( view_collection, ref, viennameta::tag<value_type>() );

                base::hook_insert( ref, viennameta::tag<value_type>() );
            }

            typedef typename base::physical_container_collection_type physical_container_collection_type;

            template<typename value_type, typename inserter_type>
            std::pair<
                typename viennagrid::storage::result_of::container_of<physical_container_collection_type, value_type>::type::hook_type,
                bool
            >
                physical_insert( const value_type & element, inserter_type & inserter )
            {
                return base::physical_insert( element, inserter );
            }

            template<typename value_type>
            std::pair<
                typename viennagrid::storage::result_of::container_of<physical_container_collection_type, value_type>::type::hook_type,
                bool
            >
                operator()( const value_type & element )
            {
                return physical_insert( element, *this );
            }

        private:
            view_collection_type & view_collection;
        };

        namespace inserter
        {
            //typedef VIENNAMETA_MAKE_TYPEMAP_1( viennagrid::storage::default_tag, viennagrid::storage::pointer_reference_tag ) pointer_reference_config;
            //typedef VIENNAMETA_MAKE_TYPEMAP_1( viennagrid::storage::default_tag, viennagrid::storage::iterator_reference_tag ) iterator_reference_config;

            template<typename dependend_inserter_type, typename container_collection_type>
            recursive_inserter_t<container_collection_type, dependend_inserter_type> get_recursive( const dependend_inserter_type & inserter, container_collection_type & collection )
            {
                return recursive_inserter_t<container_collection_type, dependend_inserter_type>(inserter, collection);
            }
        }

        namespace result_of
        {
            template<typename container_collection_type, typename dependend_inserter_type>
            struct recursive_inserter
            {
                typedef recursive_inserter_t<container_collection_type, dependend_inserter_type> type;
            };

            template<typename container_collection_type, typename id_generator_type>
            struct physical_inserter
            {
                typedef physical_inserter_t<container_collection_type, id_generator_type> type;
            };
        }

    }
}

#endif<commit_msg>adapted physical inserter to new insert_callback an added hook support<commit_after>#ifndef VIENNAGRID_STORAGE_INSERTER_HPP
#define VIENNAGRID_STORAGE_INSERTER_HPP

//#include "viennagrid/storage/reference.hpp"
#include "viennagrid/storage/container_collection.hpp"
#include "viennagrid/storage/container_collection_element.hpp"

namespace viennagrid
{
    namespace storage
    {

        template<typename container_collection_type>
        class inserter_base_t
        {
        public:
            inserter_base_t(container_collection_type & _collection) : collection(_collection) {}

        protected:
            container_collection_type & collection;
        };

        template<typename container_collection_type, typename id_generator_type__>
        class physical_inserter_t
        {
        public:
            typedef container_collection_type physical_container_collection_type;
            typedef id_generator_type__ id_generator_type;

            physical_inserter_t(container_collection_type & _collection, id_generator_type id_generator__) : collection(_collection), id_generator(id_generator__) {}

            template<typename value_type, typename inserter_type>
            std::pair<
                typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_type,
                bool
            >
                    physical_insert( value_type element, inserter_type & inserter )
            {
                typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::iterator iterator;
                typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type container_type;
                typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_tag hook_tag;
                typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_type hook_type;

                container_type & container = viennagrid::storage::container_collection::get< value_type >( collection );

                if ( !container.is_present( element ) )
                    viennagrid::storage::id::set_id(element, id_generator( viennameta::tag<value_type>() ) );

                std::pair<hook_type, bool> ret = viennagrid::storage::container_collection::get< value_type >( collection ).insert( element );

                //container.dereference_hook(ret.first).set_container(collection);

                viennagrid::storage::container_collection_element::insert_callback(
                    container.dereference_hook(ret.first),
                    ret.second,
                    inserter,
                    collection
                                                                                );

                //viennagrid::storage::container_collection_element::insert_callback(*ret.first, ret.second, inserter);

                inserter.hook_insert( ret.first, viennameta::tag<value_type>() );

                return ret;
            }

            template<typename hook_type, typename value_type>
            void hook_insert( hook_type ref, viennameta::tag<value_type> )
            {}

            template<typename value_type>
            std::pair<
                typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_type,
                bool
            >
                operator()( const value_type & element )
            {
                return physical_insert( element, *this );
            }

        private:
            container_collection_type & collection;
            id_generator_type id_generator;
        };

        template<typename view_collection_type, typename dependend_inserter_type>
        class recursive_inserter_t : public dependend_inserter_type
        {
        public:
            typedef dependend_inserter_type base;

            recursive_inserter_t(view_collection_type & _collection, const dependend_inserter_type & dependend_inserter) :
                dependend_inserter_type(dependend_inserter), view_collection(_collection) {}

            template<typename hook_type, typename value_type>
            void hook_insert( hook_type ref, viennameta::tag<value_type> )
            {
                viennagrid::storage::container_collection::hook_or_ignore( view_collection, ref, viennameta::tag<value_type>() );

                base::hook_insert( ref, viennameta::tag<value_type>() );
            }

            typedef typename base::physical_container_collection_type physical_container_collection_type;

            template<typename value_type, typename inserter_type>
            std::pair<
                typename viennagrid::storage::result_of::container_of<physical_container_collection_type, value_type>::type::hook_type,
                bool
            >
                physical_insert( const value_type & element, inserter_type & inserter )
            {
                return base::physical_insert( element, inserter );
            }

            template<typename value_type>
            std::pair<
                typename viennagrid::storage::result_of::container_of<physical_container_collection_type, value_type>::type::hook_type,
                bool
            >
                operator()( const value_type & element )
            {
                return physical_insert( element, *this );
            }

        private:
            view_collection_type & view_collection;
        };

        namespace inserter
        {
            //typedef VIENNAMETA_MAKE_TYPEMAP_1( viennagrid::storage::default_tag, viennagrid::storage::pointer_reference_tag ) pointer_reference_config;
            //typedef VIENNAMETA_MAKE_TYPEMAP_1( viennagrid::storage::default_tag, viennagrid::storage::iterator_reference_tag ) iterator_reference_config;

            template<typename dependend_inserter_type, typename container_collection_type>
            recursive_inserter_t<container_collection_type, dependend_inserter_type> get_recursive( const dependend_inserter_type & inserter, container_collection_type & collection )
            {
                return recursive_inserter_t<container_collection_type, dependend_inserter_type>(inserter, collection);
            }
        }

        namespace result_of
        {
            template<typename container_collection_type, typename dependend_inserter_type>
            struct recursive_inserter
            {
                typedef recursive_inserter_t<container_collection_type, dependend_inserter_type> type;
            };

            template<typename container_collection_type, typename id_generator_type>
            struct physical_inserter
            {
                typedef physical_inserter_t<container_collection_type, id_generator_type> type;
            };
        }

    }
}

#endif<|endoftext|>