<commit_before>/* $Id$ */

/* generate_defs_gtk.cc
 *
 * Copyright (C) 2001 The Free Software Foundation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this library; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "generate_extra_defs.h"
#include <glib.h>

int main()
{
  // g_type_init() is deprecated as of 2.36.
  // g_type_init();

  std::cout << get_defs( G_TYPE_DATE )
            << get_defs( G_TYPE_IO_CHANNEL )
            << get_defs( G_TYPE_REGEX )
            << get_defs( G_TYPE_VARIANT )
            << get_defs( G_TYPE_VARIANT_DICT )
            << std::endl;

  return 0;
}
<commit_msg>genereate_defs_glib: Add some more glib GTypes.<commit_after>/* $Id$ */

/* generate_defs_gtk.cc
 *
 * Copyright (C) 2001 The Free Software Foundation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this library; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "generate_extra_defs.h"
#include <glib.h>

int main()
{
  // g_type_init() is deprecated as of 2.36.
  // g_type_init();

  std::cout << get_defs( G_TYPE_BYTES )
            << get_defs( G_TYPE_CHECKSUM )
            << get_defs( G_TYPE_DATE )
            << get_defs( G_TYPE_DATE_TIME )
            << get_defs( G_TYPE_IO_CHANNEL )
            << get_defs( G_TYPE_KEY_FILE )
            << get_defs( G_TYPE_MAIN_CONTEXT )
            << get_defs( G_TYPE_MAIN_LOOP )
            << get_defs( G_TYPE_MATCH_INFO )
            << get_defs( G_TYPE_REGEX )
            << get_defs( G_TYPE_SOURCE )
            << get_defs( G_TYPE_THREAD )
            << get_defs( G_TYPE_VARIANT )
            << get_defs( G_TYPE_VARIANT_BUILDER )
            << get_defs( G_TYPE_VARIANT_DICT )
            << std::endl;

  return 0;
}
<|endoftext|>


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

#ifndef FORMS_COMPONENT_NAVIGATION_BAR_HXX
#define FORMS_COMPONENT_NAVIGATION_BAR_HXX

#ifndef _FORMS_FORMCOMPONENT_HXX_
#include "FormComponent.hxx"
#endif

#ifndef _COM_SUN_STAR_IO_XPERSISTOBJECT_HPP_
#include <com/sun/star/io/XPersistObject.hpp>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef COMPHELPER_PROPERTYCONTAINERHELPER_HXX
#include <comphelper/propertycontainerhelper.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XSET_HPP_
#include <com/sun/star/container/XSet.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_
#include <com/sun/star/container/XContainer.hpp>
#endif
#ifndef FORMS_SOURCE_COMPONENT_FORMCONTROLFONT_HXX
#include "formcontrolfont.hxx"
#endif

#include <set>

//.........................................................................
namespace frm
{
//.........................................................................

    //==================================================================
    // ONavigationBarModel
    //==================================================================
    typedef ::cppu::ImplHelper1 <   ::com::sun::star::awt::XControlModel
                                > ONavigationBarModel_BASE;

    class ONavigationBarModel
                        :public OControlModel
                        ,public FontControlModel
                        ,public OPropertyContainerHelper
                        ,public ONavigationBarModel_BASE
    {
        // <properties>
        ::com::sun::star::uno::Any          m_aTabStop;
        ::com::sun::star::uno::Any          m_aBackgroundColor;
        ::rtl::OUString                     m_sDefaultControl;
        ::rtl::OUString                     m_sHelpText;
        ::rtl::OUString                     m_sHelpURL;
        sal_Int16                           m_nIconSize;
        sal_Int16                           m_nBorder;
        sal_Int32                           m_nDelay;
        sal_Bool                            m_bEnabled;
        sal_Bool                            m_bShowPosition;
        sal_Bool                            m_bShowNavigation;
        sal_Bool                            m_bShowActions;
        sal_Bool                            m_bShowFilterSort;
        // </properties>

    public:
        DECLARE_DEFAULT_LEAF_XTOR( ONavigationBarModel );

        // XServiceInfo - static version
        static  ::rtl::OUString SAL_CALL getImplementationName_Static();
        static  ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames_Static();
        static  ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL Create( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory );

    protected:
        // UNO
        DECLARE_UNO3_AGG_DEFAULTS( ONavigationBarModel, OControlModel );
        virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException);

        // XServiceInfo
        virtual ::rtl::OUString SAL_CALL getImplementationName()  throw(::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()  throw(::com::sun::star::uno::RuntimeException);

        // XTypeProvider
        DECLARE_XTYPEPROVIDER()

        // OComponentHelper
        virtual void SAL_CALL disposing();

        // XPersistObject
        virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);

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

        // XPropertyState
        virtual ::com::sun::star::uno::Any getPropertyDefaultByHandle( sal_Int32 nHandle ) const;

        // OControlModel's property handling
        virtual void describeFixedProperties(
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps
        ) const;

        // prevent method hiding
        using OControlModel::disposing;
        using OControlModel::getFastPropertyValue;

    protected:
        DECLARE_XCLONEABLE();

    private:
        void implInitPropertyContainer();
    };

//.........................................................................
}   // namespace frm
//.........................................................................

#endif // FORMS_COMPONENT_NAVIGATION_BAR_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.5.82); FILE MERGED 2008/04/01 15:16:34 thb 1.5.82.3: #i85898# Stripping all external header guards 2008/04/01 12:30:26 thb 1.5.82.2: #i85898# Stripping all external header guards 2008/03/31 13:11:37 rt 1.5.82.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: navigationbar.hxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef FORMS_COMPONENT_NAVIGATION_BAR_HXX
#define FORMS_COMPONENT_NAVIGATION_BAR_HXX

#include "FormComponent.hxx"
#include <com/sun/star/io/XPersistObject.hpp>
#include <comphelper/proparrhlp.hxx>
#include <comphelper/propertycontainerhelper.hxx>
#include <cppuhelper/implbase1.hxx>
#include <cppuhelper/interfacecontainer.hxx>
#include <com/sun/star/container/XSet.hpp>
#include <com/sun/star/container/XContainer.hpp>
#include "formcontrolfont.hxx"

#include <set>

//.........................................................................
namespace frm
{
//.........................................................................

    //==================================================================
    // ONavigationBarModel
    //==================================================================
    typedef ::cppu::ImplHelper1 <   ::com::sun::star::awt::XControlModel
                                > ONavigationBarModel_BASE;

    class ONavigationBarModel
                        :public OControlModel
                        ,public FontControlModel
                        ,public OPropertyContainerHelper
                        ,public ONavigationBarModel_BASE
    {
        // <properties>
        ::com::sun::star::uno::Any          m_aTabStop;
        ::com::sun::star::uno::Any          m_aBackgroundColor;
        ::rtl::OUString                     m_sDefaultControl;
        ::rtl::OUString                     m_sHelpText;
        ::rtl::OUString                     m_sHelpURL;
        sal_Int16                           m_nIconSize;
        sal_Int16                           m_nBorder;
        sal_Int32                           m_nDelay;
        sal_Bool                            m_bEnabled;
        sal_Bool                            m_bShowPosition;
        sal_Bool                            m_bShowNavigation;
        sal_Bool                            m_bShowActions;
        sal_Bool                            m_bShowFilterSort;
        // </properties>

    public:
        DECLARE_DEFAULT_LEAF_XTOR( ONavigationBarModel );

        // XServiceInfo - static version
        static  ::rtl::OUString SAL_CALL getImplementationName_Static();
        static  ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames_Static();
        static  ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL Create( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory );

    protected:
        // UNO
        DECLARE_UNO3_AGG_DEFAULTS( ONavigationBarModel, OControlModel );
        virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException);

        // XServiceInfo
        virtual ::rtl::OUString SAL_CALL getImplementationName()  throw(::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()  throw(::com::sun::star::uno::RuntimeException);

        // XTypeProvider
        DECLARE_XTYPEPROVIDER()

        // OComponentHelper
        virtual void SAL_CALL disposing();

        // XPersistObject
        virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);

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

        // XPropertyState
        virtual ::com::sun::star::uno::Any getPropertyDefaultByHandle( sal_Int32 nHandle ) const;

        // OControlModel's property handling
        virtual void describeFixedProperties(
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps
        ) const;

        // prevent method hiding
        using OControlModel::disposing;
        using OControlModel::getFastPropertyValue;

    protected:
        DECLARE_XCLONEABLE();

    private:
        void implInitPropertyContainer();
    };

//.........................................................................
}   // namespace frm
//.........................................................................

#endif // FORMS_COMPONENT_NAVIGATION_BAR_HXX

<|endoftext|>


<commit_before>// Copyright 2019 Open GEE Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Methods for keeping track of quadtree bounds and writing them to a JSON file.

#include "fusion/portableglobe/shared/bounds_tracker.h"
#include <fstream>  // NOLINT(readability/streams)
#include <iostream>  // NOLINT(readability/streams)
#include <string>
#include "common/khFileUtils.h"
#include "common/khSimpleException.h"
#include "fusion/portableglobe/quadtree/qtutils.h"
#include "fusion/portableglobe/shared/packetbundle.h"

namespace fusion_portableglobe {

BoundsTracker::BoundsTracker() {}

void BoundsTracker::update(uint16_t channel_id, PacketType type, const std::string& qtpath) {
  std::string real_path = "0" + qtpath;

  uint32_t column, row, zoom;
  ConvertFromQtNode(real_path, &column, &row, &zoom);

  uint32_t level = qtpath.size();

  if (channels.count(channel_id) == 0) {
    channels[channel_id] = {channel_id, type, row, column, level};

  } else {
    channel_info& channel = channels[channel_id];

    // BoundsTracker only tracks bounds at the maximum zoom level (max_level)
    if (level < channel.min_level) {
      channel.min_level = level;

      // If this node is at a new max_level then set max_level and also update the bounds
      // to be the current row and column.
    } else if (level > channel.max_level) {
      channel.max_level = level;
      channel.left = channel.right = column;
      channel.top = channel.bottom = row;

      // A new node at max_level, so expand the bounding box if necessary.
    } else if (level == channel.max_level) {
      channel.left = std::min(column, channel.left);
      channel.right = std::max(column, channel.right);
      channel.top = std::min(row, channel.top);
      channel.bottom = std::max(row, channel.bottom);
    }
  }
}

void BoundsTracker::write_json_file(const std::string& filename) const {
  khEnsureParentDir(filename);

  static const std::map<PacketType, std::string> channel_type_strings =
    {{ kDbRootPacket,  "DbRoot"},
     { kDbRoot2Packet, "DbRoot2"},
     { kQtpPacket,     "Qtp"},
     { kQtp2Packet,    "Qtp2"},
     { kImagePacket,   "Image"},
     { kTerrainPacket, "Terrain"},
     { kVectorPacket,  "Vector"}};

  std::ofstream fout(filename.c_str());

  // Find the last entry so the last comma can be skipped
  auto last_entry = channels.end();
  --last_entry;

  fout << "[\n";
  for (auto iter =  channels.begin(); iter != channels.end(); ++iter) {

    const std::pair<uint16_t, channel_info> &channel_pair = *iter;
    const auto &channel = channel_pair.second;

    fout << "  {\n"
         << "    \"channel_id\": "      << channel.channel_id << ",\n"
         << "    \"type\": \""          << channel_type_strings[channel.type] << "\",\n"
         << "    \"top\": "             << channel.top << ",\n"
         << "    \"bottom\": "          << channel.bottom << ",\n"
         << "    \"left\": "            << channel.left << ",\n"
         << "    \"right\": "           << channel.right << ",\n"
         << "    \"min_level\": "       << channel.min_level << ",\n"
         << "    \"max_level\": "       << channel.max_level << "\n"
         << "  }";

    if (iter != last_entry) {
      fout << ",";
    }
    fout << "\n";
  }
  fout << "]\n";
  fout.close();
}

const channel_info& BoundsTracker::channel(uint16_t channel_id) const {
  if (channels.count(channel_id) == 0) {
    throw khSimpleException("Channel not found in BoundsTracker: ") << channel_id;
  }
  return channels.at(channel_id);
}

}  // namespace fusion_portableglobe
<commit_msg>1302 Fix const-ness compile error.<commit_after>// Copyright 2019 Open GEE Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Methods for keeping track of quadtree bounds and writing them to a JSON file.

#include "fusion/portableglobe/shared/bounds_tracker.h"
#include <fstream>  // NOLINT(readability/streams)
#include <iostream>  // NOLINT(readability/streams)
#include <string>
#include "common/khFileUtils.h"
#include "common/khSimpleException.h"
#include "fusion/portableglobe/quadtree/qtutils.h"
#include "fusion/portableglobe/shared/packetbundle.h"

namespace fusion_portableglobe {

BoundsTracker::BoundsTracker() {}

void BoundsTracker::update(uint16_t channel_id, PacketType type, const std::string& qtpath) {
  std::string real_path = "0" + qtpath;

  uint32_t column, row, zoom;
  ConvertFromQtNode(real_path, &column, &row, &zoom);

  uint32_t level = qtpath.size();

  if (channels.count(channel_id) == 0) {
    channels[channel_id] = {channel_id, type, row, column, level};

  } else {
    channel_info& channel = channels[channel_id];

    // BoundsTracker only tracks bounds at the maximum zoom level (max_level)
    if (level < channel.min_level) {
      channel.min_level = level;

      // If this node is at a new max_level then set max_level and also update the bounds
      // to be the current row and column.
    } else if (level > channel.max_level) {
      channel.max_level = level;
      channel.left = channel.right = column;
      channel.top = channel.bottom = row;

      // A new node at max_level, so expand the bounding box if necessary.
    } else if (level == channel.max_level) {
      channel.left = std::min(column, channel.left);
      channel.right = std::max(column, channel.right);
      channel.top = std::min(row, channel.top);
      channel.bottom = std::max(row, channel.bottom);
    }
  }
}

void BoundsTracker::write_json_file(const std::string& filename) const {
  khEnsureParentDir(filename);

  static const std::map<PacketType, std::string> channel_type_strings =
    {{ kDbRootPacket,  "DbRoot"},
     { kDbRoot2Packet, "DbRoot2"},
     { kQtpPacket,     "Qtp"},
     { kQtp2Packet,    "Qtp2"},
     { kImagePacket,   "Image"},
     { kTerrainPacket, "Terrain"},
     { kVectorPacket,  "Vector"}};

  std::ofstream fout(filename.c_str());

  // Find the last entry so the last comma can be skipped
  auto last_entry = channels.end();
  --last_entry;

  fout << "[\n";
  for (auto iter =  channels.begin(); iter != channels.end(); ++iter) {

    const std::pair<uint16_t, channel_info> &channel_pair = *iter;
    const auto &channel = channel_pair.second;

    fout << "  {\n"
         << "    \"channel_id\": "      << channel.channel_id << ",\n"
         << "    \"type\": \""          << channel_type_strings.at(channel.type) << "\",\n"
         << "    \"top\": "             << channel.top << ",\n"
         << "    \"bottom\": "          << channel.bottom << ",\n"
         << "    \"left\": "            << channel.left << ",\n"
         << "    \"right\": "           << channel.right << ",\n"
         << "    \"min_level\": "       << channel.min_level << ",\n"
         << "    \"max_level\": "       << channel.max_level << "\n"
         << "  }";

    if (iter != last_entry) {
      fout << ",";
    }
    fout << "\n";
  }
  fout << "]\n";
  fout.close();
}

const channel_info& BoundsTracker::channel(uint16_t channel_id) const {
  if (channels.count(channel_id) == 0) {
    throw khSimpleException("Channel not found in BoundsTracker: ") << channel_id;
  }
  return channels.at(channel_id);
}

}  // namespace fusion_portableglobe
<|endoftext|>


<commit_before>// dune-multiscale
// Copyright Holders: Patrick Henning, Rene Milk
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DHUUNE_MSFEM_TRAITS_HH
#define DHUUNE_MSFEM_TRAITS_HH

#include <dune/multiscale/common/la_backend.hh>
#include <dune/multiscale/common/traits.hh>

#include <dune/grid/spgrid.hh>
#include <dune/grid/sgrid.hh>
#include <dune/fem/space/lagrange.hh>
#include <vector>

namespace Dune {

namespace Multiscale {
namespace MsFEM {

//! type construction for the MSFEM code
struct MsFEMTraits {
  typedef typename CommonTraits::DiscreteFunctionType::DiscreteFunctionSpaceType::FunctionSpaceType FunctionSpaceType;
  typedef Dune::SPGrid<double, CommonTraits::GridType::dimension> LocalGridType;
//  typedef Dune::SGrid<CommonTraits::GridType::dimension, CommonTraits::GridType::dimension> LocalGridType;
  typedef Fem::AdaptiveLeafGridPart<LocalGridType> LocalGridPartType;
  typedef Fem::LagrangeDiscreteFunctionSpace<FunctionSpaceType, LocalGridPartType, st_lagrangespace_order> LocalGridDiscreteFunctionSpaceType;

  typedef typename LocalGridDiscreteFunctionSpaceType::IteratorType::Entity LocalEntityType;

  typedef typename BackendChooser<LocalGridDiscreteFunctionSpaceType>::DiscreteFunctionType LocalGridDiscreteFunctionType;

  typedef typename CommonTraits::GridType::Codim<0>::Entity CoarseEntityType;
  typedef typename CommonTraits::DiscreteFunctionSpaceType::BasisFunctionSetType CoarseBaseFunctionSetType;

  typedef std::vector<std::shared_ptr<LocalGridDiscreteFunctionType>> LocalSolutionVectorType;
};

} // namespace MsFEM {
} // namespace Multiscale {
} // namespace Dune {}

namespace DMM = Dune::Multiscale::MsFEM;

#endif // DUNE_MSFEM_TRAITS_HH
<commit_msg>back to Sgrid for local probs, spgrid has missing entity issue<commit_after>// dune-multiscale
// Copyright Holders: Patrick Henning, Rene Milk
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DHUUNE_MSFEM_TRAITS_HH
#define DHUUNE_MSFEM_TRAITS_HH

#include <dune/multiscale/common/la_backend.hh>
#include <dune/multiscale/common/traits.hh>

#include <dune/grid/spgrid.hh>
#include <dune/grid/sgrid.hh>
#include <dune/fem/space/lagrange.hh>
#include <vector>

namespace Dune {

namespace Multiscale {
namespace MsFEM {

//! type construction for the MSFEM code
struct MsFEMTraits {
  typedef typename CommonTraits::DiscreteFunctionType::DiscreteFunctionSpaceType::FunctionSpaceType FunctionSpaceType;
//  typedef Dune::SPGrid<double, CommonTraits::GridType::dimension> LocalGridType;
  typedef Dune::SGrid<CommonTraits::GridType::dimension, CommonTraits::GridType::dimension> LocalGridType;
  typedef Fem::AdaptiveLeafGridPart<LocalGridType> LocalGridPartType;
  typedef Fem::LagrangeDiscreteFunctionSpace<FunctionSpaceType, LocalGridPartType, st_lagrangespace_order> LocalGridDiscreteFunctionSpaceType;

  typedef typename LocalGridDiscreteFunctionSpaceType::IteratorType::Entity LocalEntityType;

  typedef typename BackendChooser<LocalGridDiscreteFunctionSpaceType>::DiscreteFunctionType LocalGridDiscreteFunctionType;

  typedef typename CommonTraits::GridType::Codim<0>::Entity CoarseEntityType;
  typedef typename CommonTraits::DiscreteFunctionSpaceType::BasisFunctionSetType CoarseBaseFunctionSetType;

  typedef std::vector<std::shared_ptr<LocalGridDiscreteFunctionType>> LocalSolutionVectorType;
};

} // namespace MsFEM {
} // namespace Multiscale {
} // namespace Dune {}

namespace DMM = Dune::Multiscale::MsFEM;

#endif // DUNE_MSFEM_TRAITS_HH
<|endoftext|>


<commit_before>
#include "tiio_sprite.h"
#include "../toonz/tapp.h"
#include "tsystem.h"
#include "tsound.h"

#include <QProcess>
#include <QDir>
#include <QtGui/QImage>
#include <QStringList>
#include <QPainter>
#include <QTextStream>
#include "toonz/preferences.h"
#include "toonz/toonzfolders.h"

#include "trasterimage.h"
#include "timageinfo.h"

//===========================================================
//
//  TImageWriterSprite
//
//===========================================================

class TImageWriterSprite : public TImageWriter {
public:
  int m_frameIndex;

  TImageWriterSprite(const TFilePath &path, int frameIndex,
                     TLevelWriterSprite *lwg)
      : TImageWriter(path), m_frameIndex(frameIndex), m_lwg(lwg) {
    m_lwg->addRef();
  }
  ~TImageWriterSprite() { m_lwg->release(); }

  bool is64bitOutputSupported() override { return false; }
  void save(const TImageP &img) override { m_lwg->save(img, m_frameIndex); }

private:
  TLevelWriterSprite *m_lwg;
};

//===========================================================
//
//  TLevelWriterSprite;
//
//===========================================================

TLevelWriterSprite::TLevelWriterSprite(const TFilePath &path,
                                       TPropertyGroup *winfo)
    : TLevelWriter(path, winfo) {
  if (!m_properties) m_properties = new Tiio::SpriteWriterProperties();
  std::string scale = m_properties->getProperty("Scale")->getValueAsString();
  m_scale           = QString::fromStdString(scale).toInt();
  std::string topPadding =
      m_properties->getProperty("Top Padding")->getValueAsString();
  m_topPadding = QString::fromStdString(topPadding).toInt();
  std::string bottomPadding =
      m_properties->getProperty("Bottom Padding")->getValueAsString();
  m_bottomPadding = QString::fromStdString(bottomPadding).toInt();
  std::string leftPadding =
      m_properties->getProperty("Left Padding")->getValueAsString();
  m_leftPadding = QString::fromStdString(leftPadding).toInt();
  std::string rightPadding =
      m_properties->getProperty("Right Padding")->getValueAsString();
  m_rightPadding = QString::fromStdString(rightPadding).toInt();
  m_format       = QString::fromStdWString(
      ((TEnumProperty *)(m_properties->getProperty("Format")))->getValue());
  TBoolProperty *trim =
      (TBoolProperty *)m_properties->getProperty("Trim Empty Space");
  m_trim = trim->getValue();
  if (TSystem::doesExistFileOrLevel(m_path)) TSystem::deleteFile(m_path);
}

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

TLevelWriterSprite::~TLevelWriterSprite() {
  int finalWidth    = m_right - m_left + 1;
  int finalHeight   = m_bottom - m_top + 1;
  int resizedWidth  = finalWidth * m_scale / 100;
  int resizedHeight = finalHeight * m_scale / 100;
  for (QImage *image : m_images) {
    QImage copy = image->copy(m_left, m_top, finalWidth, finalHeight);
    if (m_scale != 100) {
      int width  = (copy.width() * m_scale) / 100;
      int height = (copy.height() * m_scale) / 100;
      copy       = copy.scaled(width, height);
    }
    m_imagesResized.push_back(copy);
  }
  for (QImage *image : m_images) {
    delete image;
  }
  m_images.clear();
  int horizDim          = 1;
  int vertDim           = 1;
  int vertPadding       = m_topPadding + m_bottomPadding;
  int horizPadding      = m_leftPadding + m_rightPadding;
  int totalVertPadding  = 0;
  int totalHorizPadding = 0;
  int spriteSheetWidth;
  int spriteSheetHeight;
  if (m_format == "Grid") {
    // Calculate Grid Size
    while (horizDim * horizDim < m_imagesResized.size()) horizDim++;
    totalHorizPadding = horizDim * horizPadding;
    spriteSheetWidth  = horizDim * resizedWidth + totalHorizPadding;
    vertDim           = horizDim;
    // Figure out if there is one row too many (Such as 6 images needs 3 x 2 grid)
    if (vertDim * vertDim - vertDim >= m_imagesResized.size()) {
      vertDim          = vertDim - 1;
    }
    totalVertPadding = vertDim * vertPadding;
    spriteSheetHeight = vertDim * resizedHeight + totalVertPadding;
  } else if (m_format == "Vertical") {
    spriteSheetWidth  = resizedWidth + horizPadding;
    spriteSheetHeight = m_imagesResized.size() * (resizedHeight + vertPadding);
    vertDim           = m_imagesResized.size();
  } else if (m_format == "Horizontal") {
    spriteSheetWidth  = m_imagesResized.size() * (resizedWidth + horizPadding);
    spriteSheetHeight = resizedHeight + vertPadding;
    horizDim = m_imagesResized.size();
  }

  QImage spriteSheet =
      QImage(spriteSheetWidth, spriteSheetHeight, QImage::Format_ARGB32);
  spriteSheet.fill(qRgba(0, 0, 0, 0));
  QPainter painter;
  painter.begin(&spriteSheet);
  int row    = 0;
  int column = 0;
  int rowPadding;
  int columnPadding;
  int currentImage = 0;
  while (row < vertDim) {
    while (column < horizDim) {
      rowPadding    = m_topPadding;
      columnPadding = m_leftPadding;
      rowPadding += row * vertPadding;
      columnPadding += column * horizPadding;
      painter.drawImage(column * resizedWidth + columnPadding,
                        row * resizedHeight + rowPadding,
                        m_imagesResized[currentImage]);
      currentImage++;
      column++;
      if (currentImage >= m_imagesResized.size()) break;
    }
    column = 0;
    row++;
    if (currentImage >= m_imagesResized.size()) break;
  }
  painter.end();
  QString path = m_path.getQString();
  path         = path.replace(".spritesheet", ".png");
  spriteSheet.save(path, "PNG", -1);

  path = path.replace(".png", ".txt");
  QFile file(path);
  file.open(QIODevice::WriteOnly | QIODevice::Text);
  QTextStream out(&file);
  out << "Total Images: " << m_imagesResized.size() << "\n";
  out << "Individual Image Width: " << resizedWidth << "\n";
  out << "Individual Image Height: " << resizedHeight << "\n";
  out << "Individual Image Width with Padding: " << resizedWidth + horizPadding
      << "\n";
  out << "Individual Image Height with Padding: " << resizedHeight + vertPadding
      << "\n";
  out << "Images Across: " << horizDim << "\n";
  out << "Images Down : " << vertDim << "\n";
  out << "Top Padding: " << m_topPadding << "\n";
  out << "Bottom Padding: " << m_bottomPadding << "\n";
  out << "Left Padding: " << m_leftPadding << "\n";
  out << "Right Padding: " << m_rightPadding << "\n";
  out << "Horizontal Space Between Images: " << horizPadding << "\n";
  out << "Vertical Space Between Images: " << vertPadding << "\n";

  file.close();
  m_imagesResized.clear();
}

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

TImageWriterP TLevelWriterSprite::getFrameWriter(TFrameId fid) {
  if (fid.getLetter() != 0) return TImageWriterP(0);
  int index               = fid.getNumber();
  TImageWriterSprite *iwg = new TImageWriterSprite(m_path, index, this);
  return TImageWriterP(iwg);
}

//-----------------------------------------------------------
void TLevelWriterSprite::setFrameRate(double fps) {}

void TLevelWriterSprite::saveSoundTrack(TSoundTrack *st) {}

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

void TLevelWriterSprite::save(const TImageP &img, int frameIndex) {
  m_frameIndexOrder.push_back(frameIndex);
  std::sort(m_frameIndexOrder.begin(), m_frameIndexOrder.end());
  TRasterImageP tempImage(img);
  TRasterImage *image = (TRasterImage *)tempImage->cloneImage();

  m_lx           = image->getRaster()->getLx();
  m_ly           = image->getRaster()->getLy();
  int m_bpp      = image->getRaster()->getPixelSize();
  int totalBytes = m_lx * m_ly * m_bpp;
  image->getRaster()->yMirror();

  // lock raster to get data
  image->getRaster()->lock();
  void *buffin = image->getRaster()->getRawData();
  assert(buffin);
  void *buffer = malloc(totalBytes);
  memcpy(buffer, buffin, totalBytes);

  image->getRaster()->unlock();

  // create QImage save format
  QString m_intermediateFormat = "png";
  QByteArray ba                = m_intermediateFormat.toUpper().toLatin1();
  const char *format           = ba.data();

  QImage *qi = new QImage((uint8_t *)buffer, m_lx, m_ly, QImage::Format_ARGB32);

  int l = qi->width(), r = 0, t = qi->height(), b = 0;
  if (m_trim) {
    for (int y = 0; y < qi->height(); ++y) {
      QRgb *row      = (QRgb *)qi->scanLine(y);
      bool rowFilled = false;
      for (int x = 0; x < qi->width(); ++x) {
        if (qAlpha(row[x])) {
          rowFilled = true;
          r         = std::max(r, x);
          if (l > x) {
            l = x;
            x = r;
          }
        }
      }
      if (rowFilled) {
        t = std::min(t, y);
        b = y;
      }
    }
  } else {
    l = 0;
    r = qi->width() - 1;
    t = 0;
    b = qi->height() - 1;
  }
  if (m_firstPass) {
    m_firstPass = false;
    m_left      = l;
    m_right     = r;
    m_top       = t;
    m_bottom    = b;
  } else {
    if (l < m_left) m_left     = l;
    if (r > m_right) m_right   = r;
    if (t < m_top) m_top       = t;
    if (b > m_bottom) m_bottom = b;
  }
  QImage *newQi = new QImage(m_lx, m_ly, QImage::Format_ARGB32);
  newQi->fill(qRgba(0, 0, 0, 0));
  QPainter painter(newQi);
  painter.drawImage(QPoint(0, 0), *qi);

  // Make sure to order the images according to their frame index
  // Not just what comes out first
  std::vector<int>::iterator it;
  it = find(m_frameIndexOrder.begin(), m_frameIndexOrder.end(), frameIndex);
  int pos = std::distance(m_frameIndexOrder.begin(), it);

  m_images.insert(m_images.begin() + pos, newQi);
  delete image;
  delete qi;
  free(buffer);
}

Tiio::SpriteWriterProperties::SpriteWriterProperties()
    : m_topPadding("Top Padding", 0, 100, 0)
    , m_bottomPadding("Bottom Padding", 0, 100, 0)
    , m_leftPadding("Left Padding", 0, 100, 0)
    , m_rightPadding("Right Padding", 0, 100, 0)
    , m_scale("Scale", 1, 100, 100)
    , m_format("Format")
    , m_trim("Trim Empty Space", true) {
  m_format.addValue(L"Grid");
  m_format.addValue(L"Vertical");
  m_format.addValue(L"Horizontal");
  m_format.setValue(L"Grid");
  bind(m_format);
  bind(m_topPadding);
  bind(m_bottomPadding);
  bind(m_leftPadding);
  bind(m_rightPadding);
  bind(m_scale);
  bind(m_trim);
}

// Tiio::Reader* Tiio::makeSpriteReader(){ return nullptr; }
// Tiio::Writer* Tiio::makeSpriteWriter(){ return nullptr; }<commit_msg>Allow individual frames of sprites (#1742)<commit_after>
#include "tiio_sprite.h"
#include "../toonz/tapp.h"
#include "tsystem.h"
#include "tsound.h"

#include <QProcess>
#include <QDir>
#include <QtGui/QImage>
#include <QStringList>
#include <QPainter>
#include <QTextStream>
#include "toonz/preferences.h"
#include "toonz/toonzfolders.h"

#include "trasterimage.h"
#include "timageinfo.h"

//===========================================================
//
//  TImageWriterSprite
//
//===========================================================

class TImageWriterSprite : public TImageWriter {
public:
  int m_frameIndex;

  TImageWriterSprite(const TFilePath &path, int frameIndex,
                     TLevelWriterSprite *lwg)
      : TImageWriter(path), m_frameIndex(frameIndex), m_lwg(lwg) {
    m_lwg->addRef();
  }
  ~TImageWriterSprite() { m_lwg->release(); }

  bool is64bitOutputSupported() override { return false; }
  void save(const TImageP &img) override { m_lwg->save(img, m_frameIndex); }

private:
  TLevelWriterSprite *m_lwg;
};

//===========================================================
//
//  TLevelWriterSprite;
//
//===========================================================

TLevelWriterSprite::TLevelWriterSprite(const TFilePath &path,
                                       TPropertyGroup *winfo)
    : TLevelWriter(path, winfo) {
  if (!m_properties) m_properties = new Tiio::SpriteWriterProperties();
  std::string scale = m_properties->getProperty("Scale")->getValueAsString();
  m_scale           = QString::fromStdString(scale).toInt();
  std::string topPadding =
      m_properties->getProperty("Top Padding")->getValueAsString();
  m_topPadding = QString::fromStdString(topPadding).toInt();
  std::string bottomPadding =
      m_properties->getProperty("Bottom Padding")->getValueAsString();
  m_bottomPadding = QString::fromStdString(bottomPadding).toInt();
  std::string leftPadding =
      m_properties->getProperty("Left Padding")->getValueAsString();
  m_leftPadding = QString::fromStdString(leftPadding).toInt();
  std::string rightPadding =
      m_properties->getProperty("Right Padding")->getValueAsString();
  m_rightPadding = QString::fromStdString(rightPadding).toInt();
  m_format       = QString::fromStdWString(
      ((TEnumProperty *)(m_properties->getProperty("Format")))->getValue());
  TBoolProperty *trim =
      (TBoolProperty *)m_properties->getProperty("Trim Empty Space");
  m_trim = trim->getValue();
  if (TSystem::doesExistFileOrLevel(m_path)) TSystem::deleteFile(m_path);
}

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

TLevelWriterSprite::~TLevelWriterSprite() {
  int finalWidth    = m_right - m_left + 1;
  int finalHeight   = m_bottom - m_top + 1;
  int resizedWidth  = finalWidth * m_scale / 100;
  int resizedHeight = finalHeight * m_scale / 100;
  for (QImage *image : m_images) {
    QImage copy = image->copy(m_left, m_top, finalWidth, finalHeight);
    if (m_scale != 100) {
      int width  = (copy.width() * m_scale) / 100;
      int height = (copy.height() * m_scale) / 100;
      copy       = copy.scaled(width, height);
    }
    m_imagesResized.push_back(copy);
  }
  for (QImage *image : m_images) {
    delete image;
  }
  m_images.clear();
  int horizDim          = 1;
  int vertDim           = 1;
  int vertPadding       = m_topPadding + m_bottomPadding;
  int horizPadding      = m_leftPadding + m_rightPadding;
  int totalVertPadding  = 0;
  int totalHorizPadding = 0;
  int spriteSheetWidth;
  int spriteSheetHeight;
  if (m_format == "Grid") {
    // Calculate Grid Size
    while (horizDim * horizDim < m_imagesResized.size()) horizDim++;
    totalHorizPadding = horizDim * horizPadding;
    spriteSheetWidth  = horizDim * resizedWidth + totalHorizPadding;
    vertDim           = horizDim;
    // Figure out if there is one row too many
    // (Such as 6 images needs 3 x 2 grid)
    if (vertDim * vertDim - vertDim >= m_imagesResized.size()) {
      vertDim = vertDim - 1;
    }
    totalVertPadding  = vertDim * vertPadding;
    spriteSheetHeight = vertDim * resizedHeight + totalVertPadding;
  } else if (m_format == "Vertical") {
    spriteSheetWidth  = resizedWidth + horizPadding;
    spriteSheetHeight = m_imagesResized.size() * (resizedHeight + vertPadding);
    vertDim           = m_imagesResized.size();
  } else if (m_format == "Horizontal") {
    spriteSheetWidth  = m_imagesResized.size() * (resizedWidth + horizPadding);
    spriteSheetHeight = resizedHeight + vertPadding;
    horizDim          = m_imagesResized.size();
  } else if (m_format == "Individual") {
    for (int i = 0; i < m_imagesResized.size(); i++) {
      QString path      = m_path.getQString();
      QString newEnding = "_" + QString::number(i) + ".png";
      path              = path.replace(".spritesheet", newEnding);
      m_imagesResized[i].save(path, "PNG", -1);
    }
  }
  if (m_format != "Individual") {
    QImage spriteSheet =
        QImage(spriteSheetWidth, spriteSheetHeight, QImage::Format_ARGB32);
    spriteSheet.fill(qRgba(0, 0, 0, 0));
    QPainter painter;
    painter.begin(&spriteSheet);
    int row    = 0;
    int column = 0;
    int rowPadding;
    int columnPadding;
    int currentImage = 0;
    while (row < vertDim) {
      while (column < horizDim) {
        rowPadding    = m_topPadding;
        columnPadding = m_leftPadding;
        rowPadding += row * vertPadding;
        columnPadding += column * horizPadding;
        painter.drawImage(column * resizedWidth + columnPadding,
                          row * resizedHeight + rowPadding,
                          m_imagesResized[currentImage]);
        currentImage++;
        column++;
        if (currentImage >= m_imagesResized.size()) break;
      }
      column = 0;
      row++;
      if (currentImage >= m_imagesResized.size()) break;
    }
    painter.end();
    QString path = m_path.getQString();
    path         = path.replace(".spritesheet", ".png");
    spriteSheet.save(path, "PNG", -1);

    path = path.replace(".png", ".txt");
    QFile file(path);
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out(&file);
    out << "Total Images: " << m_imagesResized.size() << "\n";
    out << "Individual Image Width: " << resizedWidth << "\n";
    out << "Individual Image Height: " << resizedHeight << "\n";
    out << "Individual Image Width with Padding: "
        << resizedWidth + horizPadding << "\n";
    out << "Individual Image Height with Padding: "
        << resizedHeight + vertPadding << "\n";
    out << "Images Across: " << horizDim << "\n";
    out << "Images Down : " << vertDim << "\n";
    out << "Top Padding: " << m_topPadding << "\n";
    out << "Bottom Padding: " << m_bottomPadding << "\n";
    out << "Left Padding: " << m_leftPadding << "\n";
    out << "Right Padding: " << m_rightPadding << "\n";
    out << "Horizontal Space Between Images: " << horizPadding << "\n";
    out << "Vertical Space Between Images: " << vertPadding << "\n";

    file.close();
  }
  m_imagesResized.clear();
}

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

TImageWriterP TLevelWriterSprite::getFrameWriter(TFrameId fid) {
  if (fid.getLetter() != 0) return TImageWriterP(0);
  int index               = fid.getNumber();
  TImageWriterSprite *iwg = new TImageWriterSprite(m_path, index, this);
  return TImageWriterP(iwg);
}

//-----------------------------------------------------------
void TLevelWriterSprite::setFrameRate(double fps) {}

void TLevelWriterSprite::saveSoundTrack(TSoundTrack *st) {}

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

void TLevelWriterSprite::save(const TImageP &img, int frameIndex) {
  m_frameIndexOrder.push_back(frameIndex);
  std::sort(m_frameIndexOrder.begin(), m_frameIndexOrder.end());
  TRasterImageP tempImage(img);
  TRasterImage *image = (TRasterImage *)tempImage->cloneImage();

  m_lx           = image->getRaster()->getLx();
  m_ly           = image->getRaster()->getLy();
  int m_bpp      = image->getRaster()->getPixelSize();
  int totalBytes = m_lx * m_ly * m_bpp;
  image->getRaster()->yMirror();

  // lock raster to get data
  image->getRaster()->lock();
  void *buffin = image->getRaster()->getRawData();
  assert(buffin);
  void *buffer = malloc(totalBytes);
  memcpy(buffer, buffin, totalBytes);

  image->getRaster()->unlock();

  // create QImage save format
  QString m_intermediateFormat = "png";
  QByteArray ba                = m_intermediateFormat.toUpper().toLatin1();
  const char *format           = ba.data();

  QImage *qi = new QImage((uint8_t *)buffer, m_lx, m_ly, QImage::Format_ARGB32);

  int l = qi->width(), r = 0, t = qi->height(), b = 0;
  if (m_trim) {
    for (int y = 0; y < qi->height(); ++y) {
      QRgb *row      = (QRgb *)qi->scanLine(y);
      bool rowFilled = false;
      for (int x = 0; x < qi->width(); ++x) {
        if (qAlpha(row[x])) {
          rowFilled = true;
          r         = std::max(r, x);
          if (l > x) {
            l = x;
            x = r;
          }
        }
      }
      if (rowFilled) {
        t = std::min(t, y);
        b = y;
      }
    }
  } else {
    l = 0;
    r = qi->width() - 1;
    t = 0;
    b = qi->height() - 1;
  }
  if (m_firstPass) {
    m_firstPass = false;
    m_left      = l;
    m_right     = r;
    m_top       = t;
    m_bottom    = b;
  } else {
    if (l < m_left) m_left     = l;
    if (r > m_right) m_right   = r;
    if (t < m_top) m_top       = t;
    if (b > m_bottom) m_bottom = b;
  }
  QImage *newQi = new QImage(m_lx, m_ly, QImage::Format_ARGB32);
  newQi->fill(qRgba(0, 0, 0, 0));
  QPainter painter(newQi);
  painter.drawImage(QPoint(0, 0), *qi);

  // Make sure to order the images according to their frame index
  // Not just what comes out first
  std::vector<int>::iterator it;
  it = find(m_frameIndexOrder.begin(), m_frameIndexOrder.end(), frameIndex);
  int pos = std::distance(m_frameIndexOrder.begin(), it);

  m_images.insert(m_images.begin() + pos, newQi);
  delete image;
  delete qi;
  free(buffer);
}

Tiio::SpriteWriterProperties::SpriteWriterProperties()
    : m_topPadding("Top Padding", 0, 100, 0)
    , m_bottomPadding("Bottom Padding", 0, 100, 0)
    , m_leftPadding("Left Padding", 0, 100, 0)
    , m_rightPadding("Right Padding", 0, 100, 0)
    , m_scale("Scale", 1, 100, 100)
    , m_format("Format")
    , m_trim("Trim Empty Space", true) {
  m_format.addValue(L"Grid");
  m_format.addValue(L"Vertical");
  m_format.addValue(L"Horizontal");
  m_format.addValue(L"Individual");
  m_format.setValue(L"Grid");
  bind(m_format);
  bind(m_topPadding);
  bind(m_bottomPadding);
  bind(m_leftPadding);
  bind(m_rightPadding);
  bind(m_scale);
  bind(m_trim);
}

// Tiio::Reader* Tiio::makeSpriteReader(){ return nullptr; }
// Tiio::Writer* Tiio::makeSpriteWriter(){ return nullptr; }<|endoftext|>


<commit_before>#pragma once

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#define panic(x...) do \
{ \
	fprintf(stderr, "============panic===========\n"); \
	fprintf(stderr, x); \
	fprintf(stderr, "============================\n"); \
	exit(1); \
} while(0)

#define panic_if(cond, x...) \
		do { if ((cond)) panic(x); } while(0)

static inline char *xstrdup(const char *s)
{
	char *out = strdup(s);

	panic_if(!out, "strdup failed");

	return out;
}
<commit_msg>utils: Add warning and error message output<commit_after>#pragma once

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#define error(x...) do \
{ \
	fprintf(stderr, "Error: "); \
	fprintf(stderr, x); \
} while(0)

#define warning(x...) do \
{ \
	fprintf(stderr, "Warning: "); \
	fprintf(stderr, x); \
} while(0)

#define panic(x...) do \
{ \
	error(x); \
	exit(1); \
} while(0)

#define panic_if(cond, x...) \
		do { if ((cond)) panic(x); } while(0)

static inline char *xstrdup(const char *s)
{
	char *out = strdup(s);

	panic_if(!out, "strdup failed");

	return out;
}
<|endoftext|>


<commit_before>// Copyright 2015, University of Freiburg,
// Chair of Algorithms and Data Structures.
// Author: Björn Buchhold (buchhold@informatik.uni-freiburg.de)

#include <algorithm>
#include "DocsDB.h"
#include "../global/Constants.h"

// _____________________________________________________________________________
void DocsDB::init(const string& fileName) {
  _dbFile.open(fileName.c_str(), "r");
  if (_dbFile.empty()) {
    _size = 0;
  } else {
    off_t posLastOfft = _dbFile.getLastOffset(&_startOfOffsets);
    _size = (posLastOfft - _startOfOffsets) / sizeof(off_t);
  }
}

// _____________________________________________________________________________
string DocsDB::getTextExcerpt(Id cid) const {
  off_t ft[2];
  off_t& from = ft[0];
  off_t& to = ft[1];
  off_t at = _startOfOffsets + cid * sizeof(off_t);
  at += _dbFile.read(ft, sizeof(ft), at);
  while(to == from) {
    at += _dbFile.read(&to, sizeof(off_t), at);
  }
  assert(to > from);
  size_t nofBytes = static_cast<size_t>(to - from);
  string line(nofBytes, '\0');
  _dbFile.read(&line.front(), nofBytes, from);
  return line;
}
<commit_msg>Add TODO for C++17 non-const data()<commit_after>// Copyright 2015, University of Freiburg,
// Chair of Algorithms and Data Structures.
// Author: Björn Buchhold (buchhold@informatik.uni-freiburg.de)

#include <algorithm>
#include "DocsDB.h"
#include "../global/Constants.h"

// _____________________________________________________________________________
void DocsDB::init(const string& fileName) {
  _dbFile.open(fileName.c_str(), "r");
  if (_dbFile.empty()) {
    _size = 0;
  } else {
    off_t posLastOfft = _dbFile.getLastOffset(&_startOfOffsets);
    _size = (posLastOfft - _startOfOffsets) / sizeof(off_t);
  }
}

// _____________________________________________________________________________
string DocsDB::getTextExcerpt(Id cid) const {
  off_t ft[2];
  off_t& from = ft[0];
  off_t& to = ft[1];
  off_t at = _startOfOffsets + cid * sizeof(off_t);
  at += _dbFile.read(ft, sizeof(ft), at);
  while(to == from) {
    at += _dbFile.read(&to, sizeof(off_t), at);
  }
  assert(to > from);
  size_t nofBytes = static_cast<size_t>(to - from);
  string line(nofBytes, '\0');
  // TODO in C++17 we'll get non-const pointer std::string::data() use it the
  _dbFile.read(&line.front(), nofBytes, from);
  return line;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <gphoto2/gphoto2.h>

#define GP_SAFE( retval ) ( gp_safe( (retval) ) )

inline void gp_safe(int gp_code) {
	if (gp_code != GP_OK) {
		fprintf(stderr, "*** ERROR %i ***\n", gp_code);
		// maybe be more graceful?
		exit(1);
	}
}

// from libgphoto2 focus.c
int camera_auto_focus(Camera *camera, GPContext *context) {
	CameraWidget *widget = NULL, *child = NULL;
	CameraWidgetType type;
	int ret, val;

	ret = gp_camera_get_config(camera, &widget, context);
	if (ret < GP_OK) return ret;

	ret = gp_widget_get_child_by_name(widget, "autofocusdrive", &child);
	if (ret < GP_OK) goto caf_out;

	ret = gp_widget_get_type(child, &type);
	if (ret < GP_OK) goto caf_out;

	if (type != GP_WIDGET_TOGGLE) {
		ret = GP_ERROR_BAD_PARAMETERS;
		goto caf_out;
	}

	ret = gp_widget_get_value(child, &val);
	if (ret < GP_OK) goto caf_out;

	val++;
	ret = gp_widget_set_value(child, &val);
	if (ret < GP_OK) goto caf_out;

	ret = gp_camera_set_config(camera, widget, context);

caf_out:
	// clean up
	gp_widget_free(widget);
	return ret;
}

// from libgphoto2 sample.h
static void ctx_error_func(GPContext *context, const char *str, void *data) {
	fprintf(stderr, "\n*** Contexterror ***              \n%s\n",str);
	fflush(stderr);
}

// from libgphoto2 sample.h
static void ctx_status_func(GPContext *context, const char *str, void *data) {
	fprintf(stderr, "%s\n", str);
	fflush(stderr);
}

int main() {
	Camera *camera;
	CameraFile *previewFile;
	GPContext *cam_context;
	int retval;
	const size_t file_name_len = 256;
  const char fname[file_name_len] = "cudaPic";

	gp_camera_new(&camera);

	// create context
	cam_context = gp_context_new();
	gp_context_set_error_func(cam_context, ctx_error_func, NULL);
	gp_context_set_status_func(cam_context, ctx_status_func, NULL);

	// init camera
	printf("Camera init\n");
	GP_SAFE( gp_camera_init(camera, cam_context) );

	// get preview image
	GP_SAFE( gp_file_new(&previewFile) );
	camera_auto_focus(camera, cam_context);
	GP_SAFE( gp_camera_capture_preview(camera, previewFile, cam_context) );
	// get a filename
	{
		int i;
		i = 0;
		char file_name[file_name_len];
		FILE *fd = NULL;
		do {
			file_name[0] = '\0';
			strncpy(file_name, fname, file_name_len);
			snprintf(file_name, file_name_len, "%s_%08d", fname, i);
			strncat (file_name, ".jpg", file_name_len);
			fd = fopen(file_name, "r");
			if (fd) {
				// file exists, continue the loop
				if (fclose(fd) != 0) {
					// error
				}
				fd = NULL;
				i++;
				continue;
			} else if (errno == ENOENT) {
				// the file does not exist
				// TODO this is not atomic
				GP_SAFE( gp_file_save(previewFile, file_name) );
				break;
				// TODO check return codes
			} else {
				// other error
				return -1;
			}
		} while (true);
	}

	// clean up
	gp_file_unref(previewFile);
	gp_camera_exit(camera, cam_context);

	return 0;
}
<commit_msg>indent<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <gphoto2/gphoto2.h>

#define GP_SAFE( retval ) ( gp_safe( (retval) ) )

inline void gp_safe(int gp_code) {
	if (gp_code != GP_OK) {
		fprintf(stderr, "*** ERROR %i ***\n", gp_code);
		// maybe be more graceful?
		exit(1);
	}
}

// from libgphoto2 focus.c
int camera_auto_focus(Camera *camera, GPContext *context) {
	CameraWidget *widget = NULL, *child = NULL;
	CameraWidgetType type;
	int ret, val;

	ret = gp_camera_get_config(camera, &widget, context);
	if (ret < GP_OK)
		return ret;

	ret = gp_widget_get_child_by_name(widget, "autofocusdrive", &child);
	if (ret < GP_OK)
		goto caf_out;

	ret = gp_widget_get_type(child, &type);
	if (ret < GP_OK)
		goto caf_out;

	if (type != GP_WIDGET_TOGGLE) {
		ret = GP_ERROR_BAD_PARAMETERS;
		goto caf_out;
	}

	ret = gp_widget_get_value(child, &val);
	if (ret < GP_OK)
		goto caf_out;

	val++;
	ret = gp_widget_set_value(child, &val);
	if (ret < GP_OK)
		goto caf_out;

	ret = gp_camera_set_config(camera, widget, context);

caf_out:
	// clean up
	gp_widget_free(widget);
	return ret;
}

// from libgphoto2 sample.h
static void ctx_error_func(GPContext *context, const char *str, void *data) {
	fprintf(stderr, "\n*** Contexterror ***              \n%s\n",str);
	fflush(stderr);
}

// from libgphoto2 sample.h
static void ctx_status_func(GPContext *context, const char *str, void *data) {
	fprintf(stderr, "%s\n", str);
	fflush(stderr);
}

int main() {
	Camera *camera;
	CameraFile *previewFile;
	GPContext *cam_context;
	int retval;
	const size_t file_name_len = 256;
  const char fname[file_name_len] = "cudaPic";

	gp_camera_new(&camera);

	// create context
	cam_context = gp_context_new();
	gp_context_set_error_func(cam_context, ctx_error_func, NULL);
	gp_context_set_status_func(cam_context, ctx_status_func, NULL);

	// init camera
	printf("Camera init\n");
	GP_SAFE( gp_camera_init(camera, cam_context) );

	// get preview image
	GP_SAFE( gp_file_new(&previewFile) );
	camera_auto_focus(camera, cam_context);
	GP_SAFE( gp_camera_capture_preview(camera, previewFile, cam_context) );
	// get a filename
	{
		int i;
		i = 0;
		char file_name[file_name_len];
		FILE *fd = NULL;
		do {
			file_name[0] = '\0';
			strncpy(file_name, fname, file_name_len);
			snprintf(file_name, file_name_len, "%s_%08d", fname, i);
			strncat (file_name, ".jpg", file_name_len);
			fd = fopen(file_name, "r");
			if (fd) {
				// file exists, continue the loop
				if (fclose(fd) != 0) {
					// error
				}
				fd = NULL;
				i++;
				continue;
			} else if (errno == ENOENT) {
				// the file does not exist
				// TODO this is not atomic
				GP_SAFE( gp_file_save(previewFile, file_name) );
				break;
				// TODO check return codes
			} else {
				// other error
				return -1;
			}
		} while (true);
	}

	// clean up
	gp_file_unref(previewFile);
	gp_camera_exit(camera, cam_context);

	return 0;
}
<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2014 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "GPUImage.h"

#include "../base/Exception.h"
#include "../base/ObjectCounter.h"

#include "../graphics/Filterfliprgb.h"
#include "../graphics/BitmapLoader.h"
#include "../graphics/Bitmap.h"
#include "../graphics/ImageRegistry.h"
#include "../graphics/Image.h"
#include "../graphics/GLContextManager.h"

#include "OGLSurface.h"
#include "OffscreenCanvas.h"

#include <iostream>
#include <sstream>

using namespace std;

namespace avg {

GPUImage::GPUImage(OGLSurface * pSurface, const MaterialInfo& material)
    : m_sFilename(""),
      m_pSurface(pSurface),
      m_State(CPU),
      m_Source(NONE),
      m_Material(material)
{
    ObjectCounter::get()->incRef(&typeid(*this));
    assertValid();
}

GPUImage::~GPUImage()
{
    unload();
    ObjectCounter::get()->decRef(&typeid(*this));
}

void GPUImage::moveToGPU()
{
    assertValid();
    if (m_State == CPU) {
        switch (m_Source) {
            case FILE:
            case BITMAP:
                setupSurface();
                break;
            case SCENE:
                m_pSurface->create(B8G8R8X8, m_pCanvas->getTex(), MCTexturePtr(),
                        MCTexturePtr(), MCTexturePtr(), true);
                break;
            case NONE:
                break;
            default:
                AVG_ASSERT(false);
        }
        m_State = GPU;
    }
    assertValid();
}

void GPUImage::moveToCPU()
{
    assertValid();
    if (m_State == GPU) {
        m_State = CPU;
        m_pSurface->destroy();
        if (m_pImage) {
            m_pImage->decTexRef();
        }
    }
    assertValid();
}

void GPUImage::setEmpty()
{
    assertValid();
    unload();
    changeSource(NONE);
    assertValid();
}

void GPUImage::setFilename(const std::string& sFilename, Image::TextureCompression comp)
{
    assertValid();
    ImagePtr pImage = ImageRegistry::get()->getImage(sFilename);
    BitmapPtr pBmp = pImage->getBmp();
    if (comp == Image::TEXTURECOMPRESSION_B5G6R5 && pBmp->hasAlpha()) {
        pImage->decBmpRef();
        throw Exception(AVG_ERR_UNSUPPORTED,
                "B5G6R5-compressed textures with an alpha channel are not supported.");
    }
    unload();
    m_pImage = pImage;
    changeSource(FILE);

    m_sFilename = sFilename;

    switch (comp) {
        case Image::TEXTURECOMPRESSION_B5G6R5:
            /*
             * TODO
            m_pBmp = BitmapPtr(new Bitmap(pBmp->getSize(), B5G6R5, sFilename));
            if (!BitmapLoader::get()->isBlueFirst()) {
                FilterFlipRGB().applyInPlace(pBmp);
            }
            m_pBmp->copyPixels(*pBmp);
            */
            break;
        case Image::TEXTURECOMPRESSION_NONE:
            break;
        default:
            assert(false);
    }

    if (m_State == GPU) {
        m_pSurface->destroy();
        setupSurface();
    }
    assertValid();
}

void GPUImage::setBitmap(BitmapPtr pBmp, Image::TextureCompression comp)
{
    assertValid();
    if (!pBmp) {
        throw Exception(AVG_ERR_UNSUPPORTED, "setBitmap(): bitmap must not be None!");
    }
    if (comp == Image::TEXTURECOMPRESSION_B5G6R5 && pBmp->hasAlpha()) {
        throw Exception(AVG_ERR_UNSUPPORTED,
                "B5G6R5-compressed textures with an alpha channel are not supported.");
    }
    unload();
    bool bSourceChanged = changeSource(BITMAP);
    PixelFormat pf;
    switch (comp) {
        case Image::TEXTURECOMPRESSION_NONE:
            pf = pBmp->getPixelFormat();
            break;
        case Image::TEXTURECOMPRESSION_B5G6R5:
            pf = B5G6R5;
            if (!BitmapLoader::get()->isBlueFirst()) {
                FilterFlipRGB().applyInPlace(pBmp);
            }
            break;
        default:
            assert(false);
    }
    m_pImage = ImagePtr(new Image(pBmp));
    if (m_State == GPU) {
        m_pImage->incTexRef(m_Material.getUseMipmaps());
        m_pSurface->create(pf, m_pImage->getTex());
/*
        MCTexturePtr pTex = m_pSurface->getTex();
        if (bSourceChanged || m_pSurface->getSize() != m_pBmp->getSize() ||
                m_pSurface->getPixelFormat() != pf)
        {
            pTex = GLContextManager::get()->createTexture(m_pBmp->getSize(), pf,
                    m_Material.getUseMipmaps(), m_Material.getWrapSMode(),
                    m_Material.getWrapTMode());
            m_pSurface->create(pf, pTex);
        }
        GLContextManager::get()->scheduleTexUpload(pTex, m_pBmp);
*/
    }
    assertValid();
}

void GPUImage::setCanvas(OffscreenCanvasPtr pCanvas)
{
    assertValid();
    if (m_Source == SCENE && pCanvas == m_pCanvas) {
        return;
    }
    unload();
    changeSource(SCENE);
    m_pCanvas = pCanvas;
    if (m_State == GPU) {
        m_pSurface->create(B8G8R8X8, m_pCanvas->getTex(), MCTexturePtr(), MCTexturePtr(),
                MCTexturePtr(), true);
    }
    assertValid();
}

OffscreenCanvasPtr GPUImage::getCanvas() const
{
    return m_pCanvas;
}

const string& GPUImage::getFilename() const
{
    return m_sFilename;
}

BitmapPtr GPUImage::getBitmap()
{
    if (m_Source == NONE || m_Source == SCENE) {
        return BitmapPtr();
    } else {
        return BitmapPtr(new Bitmap(*m_pImage->getBmp()));
    }
}

IntPoint GPUImage::getSize()
{
    if (m_Source == NONE) {
        return IntPoint(0,0);
    } else {
        switch (m_State) {
            case CPU:
                if (m_Source == SCENE) {
                    return m_pCanvas->getSize();
                } else {
                    return m_pImage->getBmp()->getSize();
                }
            case GPU:
                return m_pSurface->getSize();
            default:
                AVG_ASSERT(false);
                return IntPoint(0,0);
        }
    }
}

PixelFormat GPUImage::getPixelFormat()
{
    PixelFormat pf;
    if (BitmapLoader::get()->isBlueFirst()) {
        pf = B8G8R8X8;
    } else {
        pf = R8G8B8X8;
    }
    if (m_Source != NONE) {
        switch (m_State) {
            case CPU:
                if (m_Source != SCENE) {
                    pf = m_pImage->getBmp()->getPixelFormat();
                }
            case GPU:
                pf = m_pSurface->getPixelFormat();
            default:
                AVG_ASSERT(false);
        }
    }
    return pf;
}

OGLSurface* GPUImage::getSurface()
{
    AVG_ASSERT(m_State == GPU);
    return m_pSurface;
}

GPUImage::State GPUImage::getState()
{
    return m_State;
}

GPUImage::Source GPUImage::getSource()
{
    return m_Source;
}

void GPUImage::setupSurface()
{
    PixelFormat pf = m_pImage->getBmp()->getPixelFormat();
    m_pImage->incTexRef(m_Material.getUseMipmaps());
    MCTexturePtr pTex = m_pImage->getTex();
    m_pSurface->create(pf, pTex);
}

bool GPUImage::changeSource(Source newSource)
{
    if (newSource != m_Source) {
        switch (m_Source) {
            case NONE:
                break;
            case FILE:
            case BITMAP:
//                m_pBmp = BitmapPtr();
                m_sFilename = "";
                break;
            case SCENE:
                m_pCanvas = OffscreenCanvasPtr();
                break;
            default:
                AVG_ASSERT(false);
        }
        m_Source = newSource;
        return true;
    } else {
        return false;
    }
}

void GPUImage::unload()
{
    if (m_pImage) {
        if (m_State == GPU) {
            m_pImage->decTexRef();
            m_pSurface->destroy();
        }
        m_pImage->decBmpRef();
        m_pImage = ImagePtr();
    }
    if (m_State == GPU) {
        m_pSurface->destroy();
    }
}

void GPUImage::assertValid() const
{
    AVG_ASSERT(m_pSurface);
    AVG_ASSERT((m_Source == FILE) == (m_sFilename != ""));
    AVG_ASSERT((m_Source == SCENE) == bool(m_pCanvas));
//    AVG_ASSERT((m_Source == FILE || m_Source == BITMAP) == bool(m_pBmp));
    switch (m_State) {
        case CPU:
            AVG_ASSERT(!(m_pSurface->isCreated()));
            break;
        case GPU:
            if (m_Source != NONE) {
                AVG_ASSERT(m_pSurface->isCreated());
            } else {
                AVG_ASSERT(!m_pSurface->isCreated());
            }
            break;
        default:
            AVG_ASSERT(false);
    }
}

}
<commit_msg>Fix crash using canvases.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2014 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "GPUImage.h"

#include "../base/Exception.h"
#include "../base/ObjectCounter.h"

#include "../graphics/Filterfliprgb.h"
#include "../graphics/BitmapLoader.h"
#include "../graphics/Bitmap.h"
#include "../graphics/ImageRegistry.h"
#include "../graphics/Image.h"
#include "../graphics/GLContextManager.h"

#include "OGLSurface.h"
#include "OffscreenCanvas.h"

#include <iostream>
#include <sstream>

using namespace std;

namespace avg {

GPUImage::GPUImage(OGLSurface * pSurface, const MaterialInfo& material)
    : m_sFilename(""),
      m_pSurface(pSurface),
      m_State(CPU),
      m_Source(NONE),
      m_Material(material)
{
    ObjectCounter::get()->incRef(&typeid(*this));
    assertValid();
}

GPUImage::~GPUImage()
{
    unload();
    ObjectCounter::get()->decRef(&typeid(*this));
}

void GPUImage::moveToGPU()
{
    assertValid();
    if (m_State == CPU) {
        switch (m_Source) {
            case FILE:
            case BITMAP:
                setupSurface();
                break;
            case SCENE:
                m_pSurface->create(B8G8R8X8, m_pCanvas->getTex(), MCTexturePtr(),
                        MCTexturePtr(), MCTexturePtr(), true);
                break;
            case NONE:
                break;
            default:
                AVG_ASSERT(false);
        }
        m_State = GPU;
    }
    assertValid();
}

void GPUImage::moveToCPU()
{
    assertValid();
    if (m_State == GPU) {
        m_State = CPU;
        m_pSurface->destroy();
        if (m_pImage) {
            m_pImage->decTexRef();
        }
    }
    assertValid();
}

void GPUImage::setEmpty()
{
    assertValid();
    unload();
    changeSource(NONE);
    assertValid();
}

void GPUImage::setFilename(const std::string& sFilename, Image::TextureCompression comp)
{
    assertValid();
    ImagePtr pImage = ImageRegistry::get()->getImage(sFilename);
    BitmapPtr pBmp = pImage->getBmp();
    if (comp == Image::TEXTURECOMPRESSION_B5G6R5 && pBmp->hasAlpha()) {
        pImage->decBmpRef();
        throw Exception(AVG_ERR_UNSUPPORTED,
                "B5G6R5-compressed textures with an alpha channel are not supported.");
    }
    unload();
    m_pImage = pImage;
    changeSource(FILE);

    m_sFilename = sFilename;

    switch (comp) {
        case Image::TEXTURECOMPRESSION_B5G6R5:
            /*
             * TODO
            m_pBmp = BitmapPtr(new Bitmap(pBmp->getSize(), B5G6R5, sFilename));
            if (!BitmapLoader::get()->isBlueFirst()) {
                FilterFlipRGB().applyInPlace(pBmp);
            }
            m_pBmp->copyPixels(*pBmp);
            */
            break;
        case Image::TEXTURECOMPRESSION_NONE:
            break;
        default:
            assert(false);
    }

    if (m_State == GPU) {
        m_pSurface->destroy();
        setupSurface();
    }
    assertValid();
}

void GPUImage::setBitmap(BitmapPtr pBmp, Image::TextureCompression comp)
{
    assertValid();
    if (!pBmp) {
        throw Exception(AVG_ERR_UNSUPPORTED, "setBitmap(): bitmap must not be None!");
    }
    if (comp == Image::TEXTURECOMPRESSION_B5G6R5 && pBmp->hasAlpha()) {
        throw Exception(AVG_ERR_UNSUPPORTED,
                "B5G6R5-compressed textures with an alpha channel are not supported.");
    }
    unload();
    bool bSourceChanged = changeSource(BITMAP);
    PixelFormat pf;
    switch (comp) {
        case Image::TEXTURECOMPRESSION_NONE:
            pf = pBmp->getPixelFormat();
            break;
        case Image::TEXTURECOMPRESSION_B5G6R5:
            pf = B5G6R5;
            if (!BitmapLoader::get()->isBlueFirst()) {
                FilterFlipRGB().applyInPlace(pBmp);
            }
            break;
        default:
            assert(false);
    }
    m_pImage = ImagePtr(new Image(pBmp));
    if (m_State == GPU) {
        m_pImage->incTexRef(m_Material.getUseMipmaps());
        m_pSurface->create(pf, m_pImage->getTex());
/*
        MCTexturePtr pTex = m_pSurface->getTex();
        if (bSourceChanged || m_pSurface->getSize() != m_pBmp->getSize() ||
                m_pSurface->getPixelFormat() != pf)
        {
            pTex = GLContextManager::get()->createTexture(m_pBmp->getSize(), pf,
                    m_Material.getUseMipmaps(), m_Material.getWrapSMode(),
                    m_Material.getWrapTMode());
            m_pSurface->create(pf, pTex);
        }
        GLContextManager::get()->scheduleTexUpload(pTex, m_pBmp);
*/
    }
    assertValid();
}

void GPUImage::setCanvas(OffscreenCanvasPtr pCanvas)
{
    assertValid();
    if (m_Source == SCENE && pCanvas == m_pCanvas) {
        return;
    }
    unload();
    changeSource(SCENE);
    m_pCanvas = pCanvas;
    if (m_State == GPU) {
        m_pSurface->create(B8G8R8X8, m_pCanvas->getTex(), MCTexturePtr(), MCTexturePtr(),
                MCTexturePtr(), true);
    }
    assertValid();
}

OffscreenCanvasPtr GPUImage::getCanvas() const
{
    return m_pCanvas;
}

const string& GPUImage::getFilename() const
{
    return m_sFilename;
}

BitmapPtr GPUImage::getBitmap()
{
    if (m_Source == NONE || m_Source == SCENE) {
        return BitmapPtr();
    } else {
        return BitmapPtr(new Bitmap(*m_pImage->getBmp()));
    }
}

IntPoint GPUImage::getSize()
{
    if (m_Source == NONE) {
        return IntPoint(0,0);
    } else {
        switch (m_State) {
            case CPU:
                if (m_Source == SCENE) {
                    return m_pCanvas->getSize();
                } else {
                    return m_pImage->getBmp()->getSize();
                }
            case GPU:
                return m_pSurface->getSize();
            default:
                AVG_ASSERT(false);
                return IntPoint(0,0);
        }
    }
}

PixelFormat GPUImage::getPixelFormat()
{
    PixelFormat pf;
    if (BitmapLoader::get()->isBlueFirst()) {
        pf = B8G8R8X8;
    } else {
        pf = R8G8B8X8;
    }
    if (m_Source != NONE) {
        switch (m_State) {
            case CPU:
                if (m_Source != SCENE) {
                    pf = m_pImage->getBmp()->getPixelFormat();
                }
            case GPU:
                pf = m_pSurface->getPixelFormat();
            default:
                AVG_ASSERT(false);
        }
    }
    return pf;
}

OGLSurface* GPUImage::getSurface()
{
    AVG_ASSERT(m_State == GPU);
    return m_pSurface;
}

GPUImage::State GPUImage::getState()
{
    return m_State;
}

GPUImage::Source GPUImage::getSource()
{
    return m_Source;
}

void GPUImage::setupSurface()
{
    PixelFormat pf = m_pImage->getBmp()->getPixelFormat();
    m_pImage->incTexRef(m_Material.getUseMipmaps());
    MCTexturePtr pTex = m_pImage->getTex();
    m_pSurface->create(pf, pTex);
}

bool GPUImage::changeSource(Source newSource)
{
    if (newSource != m_Source) {
        switch (m_Source) {
            case NONE:
                break;
            case FILE:
            case BITMAP:
//                m_pBmp = BitmapPtr();
                m_sFilename = "";
                break;
            case SCENE:
                m_pCanvas = OffscreenCanvasPtr();
                break;
            default:
                AVG_ASSERT(false);
        }
        m_Source = newSource;
        return true;
    } else {
        return false;
    }
}

void GPUImage::unload()
{
    if (m_pImage) {
        if (m_State == GPU) {
            m_pImage->decTexRef();
            m_pSurface->destroy();
        }
        m_pImage->decBmpRef();
        m_pImage = ImagePtr();
    }
    if (m_State == GPU && m_Source != NONE) {
        m_pSurface->destroy();
    }
}

void GPUImage::assertValid() const
{
    AVG_ASSERT(m_pSurface);
    AVG_ASSERT((m_Source == FILE) == (m_sFilename != ""));
    AVG_ASSERT((m_Source == SCENE) == bool(m_pCanvas));
//    AVG_ASSERT((m_Source == FILE || m_Source == BITMAP) == bool(m_pBmp));
    switch (m_State) {
        case CPU:
            AVG_ASSERT(!(m_pSurface->isCreated()));
            break;
        case GPU:
            if (m_Source != NONE) {
                AVG_ASSERT(m_pSurface->isCreated());
            } else {
                AVG_ASSERT(!m_pSurface->isCreated());
            }
            break;
        default:
            AVG_ASSERT(false);
    }
}

}
<|endoftext|>


<commit_before>//
//  poShape.cpp
//  BasicScene
//
//  Created by Stephen Varga on 3/19/14.
//
//
#include "cinder/TriMesh.h"
#include "cinder/Triangulate.h"
#include "cinder/gl/Texture.h"

#include "poShape.h"

namespace po {
    #pragma mark - Create -

    ShapeRef Shape::create()
    {
        std::shared_ptr<Shape> s = std::shared_ptr<Shape>(new Shape());

        return s;
    }

    //Texture/Image
    ShapeRef Shape::create(ci::gl::TextureRef texture)
    {
        ShapeRef s = Shape::create();
        s->setTexture(texture);
        return s;
    }

    //Rect
    ShapeRef Shape::createRect(float width, float height)
    {
        std::shared_ptr<Shape> s = std::shared_ptr<Shape>(new Shape());

        ci::Shape2d shape;
        shape.moveTo(0,0);
        shape.lineTo(width,0);
        shape.lineTo(width,height);
        shape.lineTo(0,height);
        shape.close();

        s->setCiShape2d(shape);

        return s;
    }

    ShapeRef Shape::createSquare(float size)
    {
        return createRect(size, size);
    }

    //Ellipse
    ShapeRef Shape::createEllipse(float width, float height)
    {
        std::shared_ptr<Shape> s = std::shared_ptr<Shape>(new Shape());

        //Adapted from http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
        float kappa = .5522848;
        float x = 0;
        float y = 0;
        float ox = (width / 2) * kappa; // control point offset horizontal
        float oy = (height / 2) * kappa; // control point offset vertical
        float xe = x + width;           // x-end
        float ye = y + height;           // y-end
        float xm = x + width / 2;       // x-middle
        float ym = y + height / 2;       // y-middle

        ci::Shape2d shape;

        shape.moveTo(x, height/2);
        shape.curveTo(x, ym-oy, xm - ox, y, xm, y);
        shape.curveTo(xm + ox, y, xe, ym - oy, xe, ym);
        shape.curveTo(xe, ym + oy, xm + ox, ye, xm, ye);
        shape.curveTo(xm - ox, ye, x, ym + oy, x, ym);
        shape.close();

        s->setCiShape2d(shape);

        return s;
    }

    ShapeRef Shape::createCircle(float size)
    {
        return createEllipse(size, size);
    }

    #pragma mark - Shape -
    Shape::Shape()
    :   mPrecision(100)
    ,   mTextureFitType(TextureFit::Type::NONE)
    ,   mTextureAlignment(Alignment::TOP_LEFT)
    ,   mUseVBO(true)
    {
    }

    Shape::~Shape() {
    }

    #pragma mark - ci::Shape2d -
    void Shape::setCiShape2d(ci::Shape2d shape)
    {
        mCiShape2d = shape;
        render();
    }

    #pragma mark - Drawing -
    void Shape::draw()
    {
        //Draw fill
        if(getFillEnabled()) {
            ci::gl::enableAlphaBlending();
            ci::gl::color(ci::ColorA(getFillColor(), getAppliedAlpha()));
            if(mUseVBO) {
                if(mTexture) mTexture->enableAndBind();
                ci::gl::draw(mVboMesh);
                if(mTexture) mTexture->disable();
            }

            else {
                if(mTexture) mTexture->enableAndBind();
                ci::gl::draw(mCiShape2d);
                if(mTexture) mTexture->disable();
            }
        }

        //Draw stroke
        #pragma message "Need to implement better stroke stuff"
        if(getStrokeEnabled()) {
            ci::gl::color(getStrokeColor());
            ci::gl::draw(mCiShape2d, ci::app::getWindowContentScale());
        }
    }

    #pragma mark - Texture -
    void Shape::setTexture(ci::gl::TextureRef texture, TextureFit::Type fit, po::Alignment alignment) {
        mTexture            = texture;
        mTextureFitType     = fit;
        mTextureAlignment   = alignment;

        //If we don't have an underlying shape, set it from the texture
        if(!mCiShape2d.getNumContours()) {
            mCiShape2d.moveTo(0,0);
            mCiShape2d.lineTo(texture->getWidth(), 0);
            mCiShape2d.lineTo(texture->getWidth(), texture->getHeight());
            mCiShape2d.lineTo(0,texture->getHeight());
            mCiShape2d.close();
        }

        render();
    }

    #pragma mark - Rendering/VBO Caching -
    void Shape::setUseVBO(bool useVBO)
    {
        mUseVBO = useVBO;

        if(mUseVBO) {
            render();
        } else {
            mVboMesh.reset();
        }
    }

    void Shape::render()
    {
        if(mUseVBO) {
            //Create Mesh
            ci::TriMesh2d mesh = ci::Triangulator(mCiShape2d, mPrecision).calcMesh(ci::Triangulator::WINDING_ODD);

            if(mTexture) {
                std::vector<ci::Vec2f> texCoords(mesh.getVertices().size());
                TextureFit::fitTexture(getBounds(), mTexture, mTextureFitType, mTextureAlignment, mesh.getVertices(), texCoords);
                mesh.appendTexCoords(&texCoords[0], texCoords.size());
            }

            //Create VBO Mesh
            mVboMesh = ci::gl::VboMesh::create(mesh);
        }

//        else {
//            if(mTexture) {
//                std::vector<ci::Vec2f> texCoords;
//                for(int i=0; i<mCiShape2d.getContours().size(); i++) {
//                    std::vector<ci::Vec2f> coords;
//
//                }
//
//                mCiShape2d.
//                //TextureFit::fitTexture(getBounds(), mTexture, mTextureFitType, mTextureAlignment, mesh.getVertices(), texCoords);
//
//            }
//        }
    }

    #pragma mark - Dimensions -
    bool Shape::pointInside(const ci::Vec2f &point, bool localize)
    {
        ci::Vec2f pos = localize ? globalToLocal(point) : point;
        return mCiShape2d.contains(pos);
    }

    ci::Rectf Shape::getBounds()
    {
        //if(mBoundsDirty) {
            mBounds       = mCiShape2d.calcBoundingBox();
            //mBoundsDirty = false;
        //}

        return mBounds;
    }
}<commit_msg>Flipping texture coords if texture is flipped<commit_after>//
//  poShape.cpp
//  BasicScene
//
//  Created by Stephen Varga on 3/19/14.
//
//
#include "cinder/TriMesh.h"
#include "cinder/Triangulate.h"
#include "cinder/gl/Texture.h"

#include "poShape.h"

namespace po {
    #pragma mark - Create -

    ShapeRef Shape::create()
    {
        std::shared_ptr<Shape> s = std::shared_ptr<Shape>(new Shape());

        return s;
    }

    //Texture/Image
    ShapeRef Shape::create(ci::gl::TextureRef texture)
    {
        ShapeRef s = Shape::create();
        s->setTexture(texture);
        return s;
    }

    //Rect
    ShapeRef Shape::createRect(float width, float height)
    {
        std::shared_ptr<Shape> s = std::shared_ptr<Shape>(new Shape());

        ci::Shape2d shape;
        shape.moveTo(0,0);
        shape.lineTo(width,0);
        shape.lineTo(width,height);
        shape.lineTo(0,height);
        shape.close();

        s->setCiShape2d(shape);

        return s;
    }

    ShapeRef Shape::createSquare(float size)
    {
        return createRect(size, size);
    }

    //Ellipse
    ShapeRef Shape::createEllipse(float width, float height)
    {
        std::shared_ptr<Shape> s = std::shared_ptr<Shape>(new Shape());

        //Adapted from http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
        float kappa = .5522848;
        float x = 0;
        float y = 0;
        float ox = (width / 2) * kappa; // control point offset horizontal
        float oy = (height / 2) * kappa; // control point offset vertical
        float xe = x + width;           // x-end
        float ye = y + height;           // y-end
        float xm = x + width / 2;       // x-middle
        float ym = y + height / 2;       // y-middle

        ci::Shape2d shape;

        shape.moveTo(x, height/2);
        shape.curveTo(x, ym-oy, xm - ox, y, xm, y);
        shape.curveTo(xm + ox, y, xe, ym - oy, xe, ym);
        shape.curveTo(xe, ym + oy, xm + ox, ye, xm, ye);
        shape.curveTo(xm - ox, ye, x, ym + oy, x, ym);
        shape.close();

        s->setCiShape2d(shape);

        return s;
    }

    ShapeRef Shape::createCircle(float size)
    {
        return createEllipse(size, size);
    }

    #pragma mark - Shape -
    Shape::Shape()
    :   mPrecision(100)
    ,   mTextureFitType(TextureFit::Type::NONE)
    ,   mTextureAlignment(Alignment::TOP_LEFT)
    ,   mUseVBO(true)
    {
    }

    Shape::~Shape() {
    }

    #pragma mark - ci::Shape2d -
    void Shape::setCiShape2d(ci::Shape2d shape)
    {
        mCiShape2d = shape;
        render();
    }

    #pragma mark - Drawing -
    void Shape::draw()
    {
        //Draw fill
        if(getFillEnabled()) {
            ci::gl::enableAlphaBlending();
            ci::gl::color(ci::ColorA(getFillColor(), getAppliedAlpha()));
            if(mUseVBO) {
                if(mTexture) mTexture->enableAndBind();
                ci::gl::draw(mVboMesh);
                if(mTexture) mTexture->disable();
            }

            else {
                if(mTexture) mTexture->enableAndBind();
                ci::gl::draw(mCiShape2d);
                if(mTexture) mTexture->disable();
            }
        }

        //Draw stroke
        #pragma message "Need to implement better stroke stuff"
        if(getStrokeEnabled()) {
            ci::gl::color(getStrokeColor());
            ci::gl::draw(mCiShape2d, ci::app::getWindowContentScale());
        }
    }

    #pragma mark - Texture -
    void Shape::setTexture(ci::gl::TextureRef texture, TextureFit::Type fit, po::Alignment alignment) {
        mTexture            = texture;
        mTextureFitType     = fit;
        mTextureAlignment   = alignment;

        //If we don't have an underlying shape, set it from the texture
        if(!mCiShape2d.getNumContours()) {
            mCiShape2d.moveTo(0,0);
            mCiShape2d.lineTo(texture->getWidth(), 0);
            mCiShape2d.lineTo(texture->getWidth(), texture->getHeight());
            mCiShape2d.lineTo(0,texture->getHeight());
            mCiShape2d.close();
        }

        render();
    }

    #pragma mark - Rendering/VBO Caching -
    void Shape::setUseVBO(bool useVBO)
    {
        mUseVBO = useVBO;

        if(mUseVBO) {
            render();
        } else {
            mVboMesh.reset();
        }
    }

    void Shape::render()
    {
        if(mUseVBO) {
            //Create Mesh
            ci::TriMesh2d mesh = ci::Triangulator(mCiShape2d, mPrecision).calcMesh(ci::Triangulator::WINDING_ODD);

            if(mTexture) {
                //Get the texture coords
                std::vector<ci::Vec2f> texCoords(mesh.getVertices().size());
                TextureFit::fitTexture(getBounds(), mTexture, mTextureFitType, mTextureAlignment, mesh.getVertices(), texCoords);

                //Check to see if texture is flipped, common if coming from FBO
                if(mTexture->isFlipped())
                    std::reverse(texCoords.begin(), texCoords.end());

                //Add coords to TriMesh
                mesh.appendTexCoords(&texCoords[0], texCoords.size());
            }

            //Create VBO Mesh
            mVboMesh = ci::gl::VboMesh::create(mesh);
        }
    }

    #pragma mark - Dimensions -
    bool Shape::pointInside(const ci::Vec2f &point, bool localize)
    {
        ci::Vec2f pos = localize ? globalToLocal(point) : point;
        return mCiShape2d.contains(pos);
    }

    ci::Rectf Shape::getBounds()
    {
        //if(mBoundsDirty) {
            mBounds       = mCiShape2d.calcBoundingBox();
            //mBoundsDirty = false;
        //}

        return mBounds;
    }
}<|endoftext|>