<commit_before>////////////////////////////////////////////////////////////
//
// The MIT License (MIT)
//
// Copyright (c) 2014 stevehalliwell
//
// 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.
//
////////////////////////////////////////////////////////////

template<class T>
void ResourceManager::initResource(const std::string& path){
    // Check to make sure, resource isn't already initialised.
    if(resources.find(path) == resources.end())
    {
        // If it exists already, return
        return;
    }

    // Create resource stub
    auto resourcestub = ResourceFactory::createResource(path, T::getResourceClassType());

    // Check validity
    if(resourcestub)
    {
        // Set it's alias and add it to the resource lookup
        resourcestub->setAlias(path);
        resources[path] = resourcestub;
    }
    else
    {
        Logger::logMessage("Init resource failed for ", path);
    }
}

template<class T>
std::shared_ptr<T> ResourceManager::loadResource(const std::string& name, LoadMode mode){
    //Check if exists in resource map
    if (resources.find(name) == resources.end())
    {
        //Check load mode
        //if the resource is to be loaded imediately
        if (mode == LoadMode.Block)
        {
            resources[name]->load;
            return ResourcePtr<resources[name]>;
        }
        //else add it to the load queue
        {
            loadingQueue.push(ResourcePtr<resources[name]>);
            return ResourcePtr<resources[name]>;
        }
    }
    return nullptr;
}

template<class T>
std::shared_ptr<T> ResourceManager::getResource(const std::string& name){
    return nullptr;
}

template<class T>
void ResourceManager::createErrorResource(const std::string& path){

}

template<class T>
std::shared_ptr<T> ResourceManager::getErrorResource(){
    return nullptr;
}
<commit_msg>Fixed typo in init resource<commit_after>////////////////////////////////////////////////////////////
//
// The MIT License (MIT)
//
// Copyright (c) 2014 stevehalliwell
//
// 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.
//
////////////////////////////////////////////////////////////

template<class T>
void ResourceManager::initResource(const std::string& path){
    // Check to make sure, resource isn't already initialised.
    if(resources.find(path) != resources.end())
    {
        // If it exists already, return
        return;
    }

    // Create resource stub
    auto resourcestub = ResourceFactory::createResource(path, T::getResourceClassType());

    // Check validity
    if(resourcestub)
    {
        // Set it's alias and add it to the resource lookup
        resourcestub->setAlias(path);
        resources[path] = resourcestub;
    }
    else
    {
        Logger::logMessage("Init resource failed for ", path);
    }
}

template<class T>
std::shared_ptr<T> ResourceManager::loadResource(const std::string& name, LoadMode mode){
    //Check if exists in resource map
    if (resources.find(name) == resources.end())
    {
        //Check load mode
        //if the resource is to be loaded imediately
        if (mode == LoadMode.Block)
        {
            resources[name]->load;
            return ResourcePtr<resources[name]>;
        }
        //else add it to the load queue
        {
            loadingQueue.push(ResourcePtr<resources[name]>);
            return ResourcePtr<resources[name]>;
        }
    }
    return nullptr;
}

template<class T>
std::shared_ptr<T> ResourceManager::getResource(const std::string& name){
    return nullptr;
}

template<class T>
void ResourceManager::createErrorResource(const std::string& path){

}

template<class T>
std::shared_ptr<T> ResourceManager::getErrorResource(){
    return nullptr;
}
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <shellapi.h>

#include "chrome/browser/views/tab_icon_view.h"

#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/app/theme/theme_resources.h"
#include "chrome/common/gfx/chrome_canvas.h"
#include "chrome/common/gfx/favicon_size.h"
#include "chrome/common/gfx/icon_util.h"
#include "chrome/common/resource_bundle.h"
#include "chrome/browser/tab_contents.h"
#include "chrome/app/chrome_dll_resource.h"

static bool g_initialized = false;
static SkBitmap* g_default_fav_icon = NULL;
static SkBitmap* g_throbber_frames = NULL;
static SkBitmap* g_throbber_frames_light = NULL;
static int g_throbber_frame_count;

// static
void TabIconView::InitializeIfNeeded() {
  if (!g_initialized) {
    ResourceBundle &rb = ResourceBundle::GetSharedInstance();

    // The default window icon is the application icon, not the default
    // favicon.
    std::wstring exe_path;
    PathService::Get(base::DIR_EXE, &exe_path);
    file_util::AppendToPath(&exe_path, L"chrome.exe");
    HICON app_icon = ExtractIcon(NULL, exe_path.c_str(), 0);
    g_default_fav_icon =
        IconUtil::CreateSkBitmapFromHICON(app_icon, gfx::Size(16, 16));
    DestroyIcon(app_icon);

    g_throbber_frames = rb.GetBitmapNamed(IDR_THROBBER);
    g_throbber_frames_light = rb.GetBitmapNamed(IDR_THROBBER_LIGHT);
    g_throbber_frame_count = g_throbber_frames->width() /
        g_throbber_frames->height();

    // Verify that our light and dark styles have the same number of frames.
    DCHECK(g_throbber_frame_count ==
        g_throbber_frames_light->width() / g_throbber_frames_light->height());
    g_initialized = true;
  }
}

TabIconView::TabIconView(TabContentsProvider* provider)
    : provider_(provider),
      is_light_(false),
      throbber_running_(false),
      throbber_frame_(0) {
  InitializeIfNeeded();
}

TabIconView::~TabIconView() {
}

void TabIconView::Update() {
  TabContents* contents = provider_->GetCurrentTabContents();
  if (throbber_running_) {
    // We think the tab is loading.
    if (!contents || !contents->is_loading()) {
      // Woops, tab is invalid or not loading, reset our status and schedule
      // a paint.
      throbber_running_ = false;
      SchedulePaint();
    } else {
      // The tab is still loading, increment the frame.
      throbber_frame_ = (throbber_frame_ + 1) % g_throbber_frame_count;
      SchedulePaint();
    }
  } else if (contents && contents->is_loading()) {
    // We didn't think we were loading, but the tab is loading. Reset the
    // frame and status and schedule a paint.
    throbber_running_ = true;
    throbber_frame_ = 0;
    SchedulePaint();
  }
}

void TabIconView::PaintThrobber(ChromeCanvas* canvas) {
  int image_size = g_throbber_frames->height();
  int image_offset = throbber_frame_ * image_size;
  canvas->DrawBitmapInt(is_light_ ? *g_throbber_frames_light :
                                    *g_throbber_frames,
                        image_offset, 0, image_size, image_size,
                        0, 0, image_size, image_size, false);
}

void TabIconView::PaintFavIcon(ChromeCanvas* canvas, const SkBitmap& bitmap) {
  int bw = bitmap.width();
  int bh = bitmap.height();
  if (bw <= kFavIconSize && bh <= kFavIconSize) {
    canvas->DrawBitmapInt(bitmap, (GetWidth() - kFavIconSize) / 2,
                          (GetHeight() - kFavIconSize) / 2);
  } else {
    canvas->DrawBitmapInt(bitmap, 0, 0, bw, bh, 0, 0, GetWidth(), GetHeight(),
                          true);
  }
}

void TabIconView::Paint(ChromeCanvas* canvas) {
  TabContents* contents = provider_->GetCurrentTabContents();
  bool rendered = false;

  if (contents) {
    if (throbber_running_) {
      rendered = true;
      PaintThrobber(canvas);
    } else {
      SkBitmap favicon = provider_->GetFavIcon();
      if (!favicon.isNull()) {
        rendered = true;
        PaintFavIcon(canvas, favicon);
      }
    }
  }

  if (!rendered) {
    PaintFavIcon(canvas, *g_default_fav_icon);
  }
}

void TabIconView::GetPreferredSize(CSize* out) {
  out->cx = out->cy = kFavIconSize;
}

<commit_msg>fix release bustage.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <windows.h>
#include <shellapi.h>

#include "chrome/browser/views/tab_icon_view.h"

#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/app/theme/theme_resources.h"
#include "chrome/common/gfx/chrome_canvas.h"
#include "chrome/common/gfx/favicon_size.h"
#include "chrome/common/gfx/icon_util.h"
#include "chrome/common/resource_bundle.h"
#include "chrome/browser/tab_contents.h"
#include "chrome/app/chrome_dll_resource.h"

static bool g_initialized = false;
static SkBitmap* g_default_fav_icon = NULL;
static SkBitmap* g_throbber_frames = NULL;
static SkBitmap* g_throbber_frames_light = NULL;
static int g_throbber_frame_count;

// static
void TabIconView::InitializeIfNeeded() {
  if (!g_initialized) {
    ResourceBundle &rb = ResourceBundle::GetSharedInstance();

    // The default window icon is the application icon, not the default
    // favicon.
    std::wstring exe_path;
    PathService::Get(base::DIR_EXE, &exe_path);
    file_util::AppendToPath(&exe_path, L"chrome.exe");
    HICON app_icon = ExtractIcon(NULL, exe_path.c_str(), 0);
    g_default_fav_icon =
        IconUtil::CreateSkBitmapFromHICON(app_icon, gfx::Size(16, 16));
    DestroyIcon(app_icon);

    g_throbber_frames = rb.GetBitmapNamed(IDR_THROBBER);
    g_throbber_frames_light = rb.GetBitmapNamed(IDR_THROBBER_LIGHT);
    g_throbber_frame_count = g_throbber_frames->width() /
        g_throbber_frames->height();

    // Verify that our light and dark styles have the same number of frames.
    DCHECK(g_throbber_frame_count ==
        g_throbber_frames_light->width() / g_throbber_frames_light->height());
    g_initialized = true;
  }
}

TabIconView::TabIconView(TabContentsProvider* provider)
    : provider_(provider),
      is_light_(false),
      throbber_running_(false),
      throbber_frame_(0) {
  InitializeIfNeeded();
}

TabIconView::~TabIconView() {
}

void TabIconView::Update() {
  TabContents* contents = provider_->GetCurrentTabContents();
  if (throbber_running_) {
    // We think the tab is loading.
    if (!contents || !contents->is_loading()) {
      // Woops, tab is invalid or not loading, reset our status and schedule
      // a paint.
      throbber_running_ = false;
      SchedulePaint();
    } else {
      // The tab is still loading, increment the frame.
      throbber_frame_ = (throbber_frame_ + 1) % g_throbber_frame_count;
      SchedulePaint();
    }
  } else if (contents && contents->is_loading()) {
    // We didn't think we were loading, but the tab is loading. Reset the
    // frame and status and schedule a paint.
    throbber_running_ = true;
    throbber_frame_ = 0;
    SchedulePaint();
  }
}

void TabIconView::PaintThrobber(ChromeCanvas* canvas) {
  int image_size = g_throbber_frames->height();
  int image_offset = throbber_frame_ * image_size;
  canvas->DrawBitmapInt(is_light_ ? *g_throbber_frames_light :
                                    *g_throbber_frames,
                        image_offset, 0, image_size, image_size,
                        0, 0, image_size, image_size, false);
}

void TabIconView::PaintFavIcon(ChromeCanvas* canvas, const SkBitmap& bitmap) {
  int bw = bitmap.width();
  int bh = bitmap.height();
  if (bw <= kFavIconSize && bh <= kFavIconSize) {
    canvas->DrawBitmapInt(bitmap, (GetWidth() - kFavIconSize) / 2,
                          (GetHeight() - kFavIconSize) / 2);
  } else {
    canvas->DrawBitmapInt(bitmap, 0, 0, bw, bh, 0, 0, GetWidth(), GetHeight(),
                          true);
  }
}

void TabIconView::Paint(ChromeCanvas* canvas) {
  TabContents* contents = provider_->GetCurrentTabContents();
  bool rendered = false;

  if (contents) {
    if (throbber_running_) {
      rendered = true;
      PaintThrobber(canvas);
    } else {
      SkBitmap favicon = provider_->GetFavIcon();
      if (!favicon.isNull()) {
        rendered = true;
        PaintFavIcon(canvas, favicon);
      }
    }
  }

  if (!rendered) {
    PaintFavIcon(canvas, *g_default_fav_icon);
  }
}

void TabIconView::GetPreferredSize(CSize* out) {
  out->cx = out->cy = kFavIconSize;
}

<|endoftext|>


<commit_before><commit_msg>don't try to import invalid document, fdo#79135<commit_after><|endoftext|>


<commit_before>/*
 *          Copyright Andrey Semashev 2007 - 2013.
 * Distributed under the Boost Software License, Version 1.0.
 *    (See accompanying file LICENSE_1_0.txt or copy at
 *          http://www.boost.org/LICENSE_1_0.txt)
 */
/*!
 * \file   empty_deleter.hpp
 * \author Andrey Semashev
 * \date   22.04.2007
 *
 * This header is deprecated, use boost/utility/empty_deleter.hpp instead. The header is left for
 * backward compatibility and will be removed in future versions.
 */

#ifndef BOOST_LOG_UTILITY_EMPTY_DELETER_HPP_INCLUDED_
#define BOOST_LOG_UTILITY_EMPTY_DELETER_HPP_INCLUDED_

#include <boost/utility/empty_deleter.hpp>
#include <boost/log/detail/config.hpp>

#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif

#if defined(__GNUC__)
#pragma message "Boost.Log: This header is deprecated, use boost/utility/empty_deleter.hpp instead."
#elif defined(_MSC_VER)
#pragma message("Boost.Log: This header is deprecated, use boost/utility/empty_deleter.hpp instead.")
#endif

namespace boost {

BOOST_LOG_OPEN_NAMESPACE

using boost::empty_deleter

BOOST_LOG_CLOSE_NAMESPACE // namespace log

} // namespace boost

#endif // BOOST_LOG_UTILITY_EMPTY_DELETER_HPP_INCLUDED_
<commit_msg>Fixed compilation.<commit_after>/*
 *          Copyright Andrey Semashev 2007 - 2013.
 * Distributed under the Boost Software License, Version 1.0.
 *    (See accompanying file LICENSE_1_0.txt or copy at
 *          http://www.boost.org/LICENSE_1_0.txt)
 */
/*!
 * \file   empty_deleter.hpp
 * \author Andrey Semashev
 * \date   22.04.2007
 *
 * This header is deprecated, use boost/utility/empty_deleter.hpp instead. The header is left for
 * backward compatibility and will be removed in future versions.
 */

#ifndef BOOST_LOG_UTILITY_EMPTY_DELETER_HPP_INCLUDED_
#define BOOST_LOG_UTILITY_EMPTY_DELETER_HPP_INCLUDED_

#include <boost/utility/empty_deleter.hpp>
#include <boost/log/detail/config.hpp>

#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif

#if defined(__GNUC__)
#pragma message "Boost.Log: This header is deprecated, use boost/utility/empty_deleter.hpp instead."
#elif defined(_MSC_VER)
#pragma message("Boost.Log: This header is deprecated, use boost/utility/empty_deleter.hpp instead.")
#endif

namespace boost {

BOOST_LOG_OPEN_NAMESPACE

using boost::empty_deleter;

BOOST_LOG_CLOSE_NAMESPACE // namespace log

} // namespace boost

#endif // BOOST_LOG_UTILITY_EMPTY_DELETER_HPP_INCLUDED_
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                          License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
//   * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/

#ifndef OPENCV_STITCHING_STITCHER_HPP
#define OPENCV_STITCHING_STITCHER_HPP

#include "opencv2/core.hpp"
#include "opencv2/features2d.hpp"
#include "opencv2/stitching/warpers.hpp"
#include "opencv2/stitching/detail/matchers.hpp"
#include "opencv2/stitching/detail/motion_estimators.hpp"
#include "opencv2/stitching/detail/exposure_compensate.hpp"
#include "opencv2/stitching/detail/seam_finders.hpp"
#include "opencv2/stitching/detail/blenders.hpp"
#include "opencv2/stitching/detail/camera.hpp"

/**
@defgroup stitching Images stitching

This figure illustrates the stitching module pipeline implemented in the Stitcher class. Using that
class it's possible to configure/remove some steps, i.e. adjust the stitching pipeline according to
the particular needs. All building blocks from the pipeline are available in the detail namespace,
one can combine and use them separately.

The implemented stitching pipeline is very similar to the one proposed in @cite BL07 .

![image](StitchingPipeline.jpg)

@{
    @defgroup stitching_match Features Finding and Images Matching
    @defgroup stitching_rotation Rotation Estimation
    @defgroup stitching_autocalib Autocalibration
    @defgroup stitching_warp Images Warping
    @defgroup stitching_seam Seam Estimation
    @defgroup stitching_exposure Exposure Compensation
    @defgroup stitching_blend Image Blenders
@}
  */

namespace cv {

//! @addtogroup stitching
//! @{

/** @brief High level image stitcher.

It's possible to use this class without being aware of the entire stitching pipeline. However, to
be able to achieve higher stitching stability and quality of the final images at least being
familiar with the theory is recommended.

@note
   -   A basic example on image stitching can be found at
        opencv_source_code/samples/cpp/stitching.cpp
    -   A detailed example on image stitching can be found at
        opencv_source_code/samples/cpp/stitching_detailed.cpp
 */
class CV_EXPORTS_W Stitcher
{
public:
    enum { ORIG_RESOL = -1 };
    enum Status
    {
        OK = 0,
        ERR_NEED_MORE_IMGS = 1,
        ERR_HOMOGRAPHY_EST_FAIL = 2,
        ERR_CAMERA_PARAMS_ADJUST_FAIL = 3
    };

   // Stitcher() {}
    /** @brief Creates a stitcher with the default parameters.

    @param try_use_gpu Flag indicating whether GPU should be used whenever it's possible.
    @return Stitcher class instance.
     */
    static Stitcher createDefault(bool try_use_gpu = false);

    CV_WRAP double registrationResol() const { return registr_resol_; }
    CV_WRAP void setRegistrationResol(double resol_mpx) { registr_resol_ = resol_mpx; }

    CV_WRAP double seamEstimationResol() const { return seam_est_resol_; }
    CV_WRAP void setSeamEstimationResol(double resol_mpx) { seam_est_resol_ = resol_mpx; }

    CV_WRAP double compositingResol() const { return compose_resol_; }
    CV_WRAP void setCompositingResol(double resol_mpx) { compose_resol_ = resol_mpx; }

    CV_WRAP double panoConfidenceThresh() const { return conf_thresh_; }
    CV_WRAP void setPanoConfidenceThresh(double conf_thresh) { conf_thresh_ = conf_thresh; }

    CV_WRAP bool waveCorrection() const { return do_wave_correct_; }
    CV_WRAP void setWaveCorrection(bool flag) { do_wave_correct_ = flag; }

    detail::WaveCorrectKind waveCorrectKind() const { return wave_correct_kind_; }
    void setWaveCorrectKind(detail::WaveCorrectKind kind) { wave_correct_kind_ = kind; }

    Ptr<detail::FeaturesFinder> featuresFinder() { return features_finder_; }
    const Ptr<detail::FeaturesFinder> featuresFinder() const { return features_finder_; }
    void setFeaturesFinder(Ptr<detail::FeaturesFinder> features_finder)
        { features_finder_ = features_finder; }

    Ptr<detail::FeaturesMatcher> featuresMatcher() { return features_matcher_; }
    const Ptr<detail::FeaturesMatcher> featuresMatcher() const { return features_matcher_; }
    void setFeaturesMatcher(Ptr<detail::FeaturesMatcher> features_matcher)
        { features_matcher_ = features_matcher; }

    const cv::UMat& matchingMask() const { return matching_mask_; }
    void setMatchingMask(const cv::UMat &mask)
    {
        CV_Assert(mask.type() == CV_8U && mask.cols == mask.rows);
        matching_mask_ = mask.clone();
    }

    Ptr<detail::BundleAdjusterBase> bundleAdjuster() { return bundle_adjuster_; }
    const Ptr<detail::BundleAdjusterBase> bundleAdjuster() const { return bundle_adjuster_; }
    void setBundleAdjuster(Ptr<detail::BundleAdjusterBase> bundle_adjuster)
        { bundle_adjuster_ = bundle_adjuster; }

    Ptr<WarperCreator> warper() { return warper_; }
    const Ptr<WarperCreator> warper() const { return warper_; }
    void setWarper(Ptr<WarperCreator> creator) { warper_ = creator; }

    Ptr<detail::ExposureCompensator> exposureCompensator() { return exposure_comp_; }
    const Ptr<detail::ExposureCompensator> exposureCompensator() const { return exposure_comp_; }
    void setExposureCompensator(Ptr<detail::ExposureCompensator> exposure_comp)
        { exposure_comp_ = exposure_comp; }

    Ptr<detail::SeamFinder> seamFinder() { return seam_finder_; }
    const Ptr<detail::SeamFinder> seamFinder() const { return seam_finder_; }
    void setSeamFinder(Ptr<detail::SeamFinder> seam_finder) { seam_finder_ = seam_finder; }

    Ptr<detail::Blender> blender() { return blender_; }
    const Ptr<detail::Blender> blender() const { return blender_; }
    void setBlender(Ptr<detail::Blender> b) { blender_ = b; }

    /** @overload */
    CV_WRAP Status estimateTransform(InputArrayOfArrays images);
    /** @brief These functions try to match the given images and to estimate rotations of each camera.

    @note Use the functions only if you're aware of the stitching pipeline, otherwise use
    Stitcher::stitch.

    @param images Input images.
    @param rois Region of interest rectangles.
    @return Status code.
     */
    Status estimateTransform(InputArrayOfArrays images, const std::vector<std::vector<Rect> > &rois);

    /** @overload */
    CV_WRAP Status composePanorama(OutputArray pano);
    /** @brief These functions try to compose the given images (or images stored internally from the other function
    calls) into the final pano under the assumption that the image transformations were estimated
    before.

    @note Use the functions only if you're aware of the stitching pipeline, otherwise use
    Stitcher::stitch.

    @param images Input images.
    @param pano Final pano.
    @return Status code.
     */
    Status composePanorama(InputArrayOfArrays images, OutputArray pano);

    /** @overload */
    CV_WRAP Status stitch(InputArrayOfArrays images, OutputArray pano);
    /** @brief These functions try to stitch the given images.

    @param images Input images.
    @param rois Region of interest rectangles.
    @param pano Final pano.
    @return Status code.
     */
    Status stitch(InputArrayOfArrays images, const std::vector<std::vector<Rect> > &rois, OutputArray pano);

    std::vector<int> component() const { return indices_; }
    std::vector<detail::CameraParams> cameras() const { return cameras_; }
    CV_WRAP double workScale() const { return work_scale_; }

private:
    //Stitcher() {}

    Status matchImages();
    Status estimateCameraParams();

    double registr_resol_;
    double seam_est_resol_;
    double compose_resol_;
    double conf_thresh_;
    Ptr<detail::FeaturesFinder> features_finder_;
    Ptr<detail::FeaturesMatcher> features_matcher_;
    cv::UMat matching_mask_;
    Ptr<detail::BundleAdjusterBase> bundle_adjuster_;
    bool do_wave_correct_;
    detail::WaveCorrectKind wave_correct_kind_;
    Ptr<WarperCreator> warper_;
    Ptr<detail::ExposureCompensator> exposure_comp_;
    Ptr<detail::SeamFinder> seam_finder_;
    Ptr<detail::Blender> blender_;

    std::vector<cv::UMat> imgs_;
    std::vector<std::vector<cv::Rect> > rois_;
    std::vector<cv::Size> full_img_sizes_;
    std::vector<detail::ImageFeatures> features_;
    std::vector<detail::MatchesInfo> pairwise_matches_;
    std::vector<cv::UMat> seam_est_imgs_;
    std::vector<int> indices_;
    std::vector<detail::CameraParams> cameras_;
    double work_scale_;
    double seam_scale_;
    double seam_work_aspect_;
    double warped_image_scale_;
};

CV_EXPORTS_W Ptr<Stitcher> createStitcher(bool try_use_gpu = false);

//! @} stitching

} // namespace cv

#endif // OPENCV_STITCHING_STITCHER_HPP
<commit_msg>Added warning about possible X11 macro collision<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                          License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
//   * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/

#ifndef OPENCV_STITCHING_STITCHER_HPP
#define OPENCV_STITCHING_STITCHER_HPP

#include "opencv2/core.hpp"
#include "opencv2/features2d.hpp"
#include "opencv2/stitching/warpers.hpp"
#include "opencv2/stitching/detail/matchers.hpp"
#include "opencv2/stitching/detail/motion_estimators.hpp"
#include "opencv2/stitching/detail/exposure_compensate.hpp"
#include "opencv2/stitching/detail/seam_finders.hpp"
#include "opencv2/stitching/detail/blenders.hpp"
#include "opencv2/stitching/detail/camera.hpp"

#if defined(Status)
#  warning Detected X11 'Status' macro definition, it can cause build conflicts. Please, include this header before any X11 headers.
#endif

/**
@defgroup stitching Images stitching

This figure illustrates the stitching module pipeline implemented in the Stitcher class. Using that
class it's possible to configure/remove some steps, i.e. adjust the stitching pipeline according to
the particular needs. All building blocks from the pipeline are available in the detail namespace,
one can combine and use them separately.

The implemented stitching pipeline is very similar to the one proposed in @cite BL07 .

![image](StitchingPipeline.jpg)

@{
    @defgroup stitching_match Features Finding and Images Matching
    @defgroup stitching_rotation Rotation Estimation
    @defgroup stitching_autocalib Autocalibration
    @defgroup stitching_warp Images Warping
    @defgroup stitching_seam Seam Estimation
    @defgroup stitching_exposure Exposure Compensation
    @defgroup stitching_blend Image Blenders
@}
  */

namespace cv {

//! @addtogroup stitching
//! @{

/** @brief High level image stitcher.

It's possible to use this class without being aware of the entire stitching pipeline. However, to
be able to achieve higher stitching stability and quality of the final images at least being
familiar with the theory is recommended.

@note
   -   A basic example on image stitching can be found at
        opencv_source_code/samples/cpp/stitching.cpp
    -   A detailed example on image stitching can be found at
        opencv_source_code/samples/cpp/stitching_detailed.cpp
 */
class CV_EXPORTS_W Stitcher
{
public:
    enum { ORIG_RESOL = -1 };
    enum Status
    {
        OK = 0,
        ERR_NEED_MORE_IMGS = 1,
        ERR_HOMOGRAPHY_EST_FAIL = 2,
        ERR_CAMERA_PARAMS_ADJUST_FAIL = 3
    };

   // Stitcher() {}
    /** @brief Creates a stitcher with the default parameters.

    @param try_use_gpu Flag indicating whether GPU should be used whenever it's possible.
    @return Stitcher class instance.
     */
    static Stitcher createDefault(bool try_use_gpu = false);

    CV_WRAP double registrationResol() const { return registr_resol_; }
    CV_WRAP void setRegistrationResol(double resol_mpx) { registr_resol_ = resol_mpx; }

    CV_WRAP double seamEstimationResol() const { return seam_est_resol_; }
    CV_WRAP void setSeamEstimationResol(double resol_mpx) { seam_est_resol_ = resol_mpx; }

    CV_WRAP double compositingResol() const { return compose_resol_; }
    CV_WRAP void setCompositingResol(double resol_mpx) { compose_resol_ = resol_mpx; }

    CV_WRAP double panoConfidenceThresh() const { return conf_thresh_; }
    CV_WRAP void setPanoConfidenceThresh(double conf_thresh) { conf_thresh_ = conf_thresh; }

    CV_WRAP bool waveCorrection() const { return do_wave_correct_; }
    CV_WRAP void setWaveCorrection(bool flag) { do_wave_correct_ = flag; }

    detail::WaveCorrectKind waveCorrectKind() const { return wave_correct_kind_; }
    void setWaveCorrectKind(detail::WaveCorrectKind kind) { wave_correct_kind_ = kind; }

    Ptr<detail::FeaturesFinder> featuresFinder() { return features_finder_; }
    const Ptr<detail::FeaturesFinder> featuresFinder() const { return features_finder_; }
    void setFeaturesFinder(Ptr<detail::FeaturesFinder> features_finder)
        { features_finder_ = features_finder; }

    Ptr<detail::FeaturesMatcher> featuresMatcher() { return features_matcher_; }
    const Ptr<detail::FeaturesMatcher> featuresMatcher() const { return features_matcher_; }
    void setFeaturesMatcher(Ptr<detail::FeaturesMatcher> features_matcher)
        { features_matcher_ = features_matcher; }

    const cv::UMat& matchingMask() const { return matching_mask_; }
    void setMatchingMask(const cv::UMat &mask)
    {
        CV_Assert(mask.type() == CV_8U && mask.cols == mask.rows);
        matching_mask_ = mask.clone();
    }

    Ptr<detail::BundleAdjusterBase> bundleAdjuster() { return bundle_adjuster_; }
    const Ptr<detail::BundleAdjusterBase> bundleAdjuster() const { return bundle_adjuster_; }
    void setBundleAdjuster(Ptr<detail::BundleAdjusterBase> bundle_adjuster)
        { bundle_adjuster_ = bundle_adjuster; }

    Ptr<WarperCreator> warper() { return warper_; }
    const Ptr<WarperCreator> warper() const { return warper_; }
    void setWarper(Ptr<WarperCreator> creator) { warper_ = creator; }

    Ptr<detail::ExposureCompensator> exposureCompensator() { return exposure_comp_; }
    const Ptr<detail::ExposureCompensator> exposureCompensator() const { return exposure_comp_; }
    void setExposureCompensator(Ptr<detail::ExposureCompensator> exposure_comp)
        { exposure_comp_ = exposure_comp; }

    Ptr<detail::SeamFinder> seamFinder() { return seam_finder_; }
    const Ptr<detail::SeamFinder> seamFinder() const { return seam_finder_; }
    void setSeamFinder(Ptr<detail::SeamFinder> seam_finder) { seam_finder_ = seam_finder; }

    Ptr<detail::Blender> blender() { return blender_; }
    const Ptr<detail::Blender> blender() const { return blender_; }
    void setBlender(Ptr<detail::Blender> b) { blender_ = b; }

    /** @overload */
    CV_WRAP Status estimateTransform(InputArrayOfArrays images);
    /** @brief These functions try to match the given images and to estimate rotations of each camera.

    @note Use the functions only if you're aware of the stitching pipeline, otherwise use
    Stitcher::stitch.

    @param images Input images.
    @param rois Region of interest rectangles.
    @return Status code.
     */
    Status estimateTransform(InputArrayOfArrays images, const std::vector<std::vector<Rect> > &rois);

    /** @overload */
    CV_WRAP Status composePanorama(OutputArray pano);
    /** @brief These functions try to compose the given images (or images stored internally from the other function
    calls) into the final pano under the assumption that the image transformations were estimated
    before.

    @note Use the functions only if you're aware of the stitching pipeline, otherwise use
    Stitcher::stitch.

    @param images Input images.
    @param pano Final pano.
    @return Status code.
     */
    Status composePanorama(InputArrayOfArrays images, OutputArray pano);

    /** @overload */
    CV_WRAP Status stitch(InputArrayOfArrays images, OutputArray pano);
    /** @brief These functions try to stitch the given images.

    @param images Input images.
    @param rois Region of interest rectangles.
    @param pano Final pano.
    @return Status code.
     */
    Status stitch(InputArrayOfArrays images, const std::vector<std::vector<Rect> > &rois, OutputArray pano);

    std::vector<int> component() const { return indices_; }
    std::vector<detail::CameraParams> cameras() const { return cameras_; }
    CV_WRAP double workScale() const { return work_scale_; }

private:
    //Stitcher() {}

    Status matchImages();
    Status estimateCameraParams();

    double registr_resol_;
    double seam_est_resol_;
    double compose_resol_;
    double conf_thresh_;
    Ptr<detail::FeaturesFinder> features_finder_;
    Ptr<detail::FeaturesMatcher> features_matcher_;
    cv::UMat matching_mask_;
    Ptr<detail::BundleAdjusterBase> bundle_adjuster_;
    bool do_wave_correct_;
    detail::WaveCorrectKind wave_correct_kind_;
    Ptr<WarperCreator> warper_;
    Ptr<detail::ExposureCompensator> exposure_comp_;
    Ptr<detail::SeamFinder> seam_finder_;
    Ptr<detail::Blender> blender_;

    std::vector<cv::UMat> imgs_;
    std::vector<std::vector<cv::Rect> > rois_;
    std::vector<cv::Size> full_img_sizes_;
    std::vector<detail::ImageFeatures> features_;
    std::vector<detail::MatchesInfo> pairwise_matches_;
    std::vector<cv::UMat> seam_est_imgs_;
    std::vector<int> indices_;
    std::vector<detail::CameraParams> cameras_;
    double work_scale_;
    double seam_scale_;
    double seam_work_aspect_;
    double warped_image_scale_;
};

CV_EXPORTS_W Ptr<Stitcher> createStitcher(bool try_use_gpu = false);

//! @} stitching

} // namespace cv

#endif // OPENCV_STITCHING_STITCHER_HPP
<|endoftext|>


<commit_before>/*
 * eos - A 3D Morphable Model fitting library written in modern C++11/14.
 *
 * File: include/eos/fitting/RenderingParameters.hpp
 *
 * Copyright 2016 Patrik Huber
 *
 * 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.
 */
#pragma once

#ifndef RENDERINGPARAMETERS_HPP_
#define RENDERINGPARAMETERS_HPP_

#include "eos/fitting/orthographic_camera_estimation_linear.hpp"

#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/quaternion.hpp"

#include "eos/fitting/detail/optional_cerealisation.hpp"
#include "eos/fitting/detail/glm_cerealisation.hpp"
#include "cereal/cereal.hpp"
#include "cereal/archives/json.hpp"

#include "opencv2/core/core.hpp"

#include "boost/optional.hpp"

#include <string>
#include <fstream>
#include <stdexcept>

namespace eos {
	namespace fitting {

/**
 * @brief A class representing a camera viewing frustum. At the moment only
 * fully tested with orthographic camera.
 */
struct Frustum
{
//	float l, r, b, t;
	Frustum() {};
	Frustum(float l, float r, float b, float t) : l(l), r(r), b(b), t(t) {};
	//Frustum(float l, float r, float b, float t, float n, float f) : l(l), r(r), b(b), t(t), n(n), f(f) {};
	float l = -1.0f;
	float r = 1.0f;
	float b = -1.0f;
	float t = 1.0f;
	//boost::optional<float> n; // These are not needed yet but probably will in the future,
	//boost::optional<float> f; // and then it's good if the old serialised files stay compatible.

	friend class cereal::access;
	/**
	 * Serialises this class using cereal.
	 *
	 * @param[in] ar The archive to serialise to (or to serialise from).
	 */
	template<class Archive>
	void serialize(Archive& archive)
	{
		archive(CEREAL_NVP(l), CEREAL_NVP(r), CEREAL_NVP(b), CEREAL_NVP(t));
	};
};

enum class CameraType
{
	Orthographic,
	Perspective
};

/**
 * @brief Represents a set of estimated model parameters (rotation, translation) and
 * camera parameters (viewing frustum).
 *
 * The estimated rotation and translation transform the model from model-space to camera-space,
 * and, if one wishes to use OpenGL, can be used to build the model-view matrix.
 * The parameters are the inverse of the camera position in 3D space.
 *
 * The camera frustum describes the size of the viewing plane of the camera, and
 * can be used to build an OpenGL-conformant orthographic projection matrix.
 *
 * Together, these parameters fully describe the imaging process of a given model instance
 * (under an orthographic projection).
 *
 * The rotation values are given in radians and estimated using the RPY convention.
 * Yaw is applied first to the model, then pitch, then roll (R * P * Y * vertex).
 * In general, the convention is as follows:
 * 	 r_x = Pitch
 *	 r_y = Yaw. Positive means subject is looking left (we see her right cheek).
 *	 r_z = Roll. Positive means the subject's right eye is further down than the other one (he tilts his head to the right).
 * However, we're using a quaternion now to represent the rotation, and glm::eulerAngles() will give
 * slightly different angles (according to a different (undocumented)) convention. However, the
 * rotation is exactly the same! (i.e. they are represented by the same quaternion / rotation matrix).
 *
 * This should always represent all parameters necessary to render the model to an image, and be completely OpenGL compliant.
 */
class RenderingParameters
{
public:
	// Creates with default frustum...
	RenderingParameters() {};

	// Initialisation for Eigen::LevMarq
	// This creates the correct rotation quaternion in the case the angles were estimated/given by R*P*Y*v.
	// Angles given in radian.
	// Note: If you subsequently use RP::get_rotation() and glm::eulerAngles() on it, the angles you get out will be slightly different from the ones you put in here.
	// But they will describe the same rotation! Just in a different order. (i.e. the rotation matrix or quaternion for both of these two sets of angles is identical.)
	RenderingParameters(CameraType camera_type, Frustum camera_frustum, float r_x, float r_y, float r_z, float tx, float ty, int screen_width, int screen_height) : camera_type(camera_type), frustum(camera_frustum), t_x(tx), t_y(ty), screen_width(screen_width), screen_height(screen_height) {
		auto rot_mtx_x = glm::rotate(glm::mat4(1.0f), r_x, glm::vec3{ 1.0f, 0.0f, 0.0f });
		auto rot_mtx_y = glm::rotate(glm::mat4(1.0f), r_y, glm::vec3{ 0.0f, 1.0f, 0.0f });
		auto rot_mtx_z = glm::rotate(glm::mat4(1.0f), r_z, glm::vec3{ 0.0f, 0.0f, 1.0f });
		auto zxy_rotation_matrix = rot_mtx_z * rot_mtx_x * rot_mtx_y;
		rotation = zxy_rotation_matrix;
	};

	// This assumes estimate_sop was run on points with OpenCV viewport! I.e. y flipped.
	RenderingParameters(ScaledOrthoProjectionParameters ortho_params, int image_width, int image_height) {
		camera_type = CameraType::Orthographic;
		rotation = ortho_params.R; // convert the rotation matrix to a quaternion
		t_x = ortho_params.tx;
		t_y = ortho_params.ty;
		const auto l = 0.0;
		const auto r = image_width / ortho_params.s;
		const auto b = 0.0; // The b and t values are not tested for what happens if the SOP parameters
		const auto t = image_height / ortho_params.s; // were estimated on a non-flipped viewport.
		frustum = Frustum(l, r, b, t);
	};

	glm::quat get_rotation() const {
		return rotation;
	};

	glm::mat4x4 get_modelview() const {
		glm::mat4x4 modelview = glm::mat4_cast(rotation);
		modelview[3][0] = t_x;
		modelview[3][1] = t_y;
		return modelview;
	};

	glm::mat4x4 get_projection() const {
		if (camera_type == CameraType::Orthographic)
		{
			return glm::ortho<float>(frustum.l, frustum.r, frustum.b, frustum.t);
		}
		else {
			throw std::runtime_error("get_projection() for CameraType::Perspective is not implemented yet.");
		}
	};

private:
	CameraType camera_type = CameraType::Orthographic;
	Frustum frustum; // Can construct a glm::ortho or glm::perspective matrix from this.

	glm::quat rotation;

	float t_x;
	float t_y;
	//boost::optional<float> t_z;
	//boost::optional<float> focal_length; // only for certain camera types. Should it go into Frustum?

	int screen_width; // (why) do we need these?
	int screen_height;

	friend class cereal::access;
	/**
	 * Serialises this class using cereal.
	 *
	 * @param[in] ar The archive to serialise to (or to serialise from).
	 */
	template<class Archive>
	void serialize(Archive& archive)
	{
		archive(CEREAL_NVP(camera_type), CEREAL_NVP(frustum), CEREAL_NVP(rotation), CEREAL_NVP(t_x), CEREAL_NVP(t_y), CEREAL_NVP(screen_width), CEREAL_NVP(screen_height));
	};
};

/**
 * Saves the rendering parameters for an image to a json file.
 *
 * @param[in] rendering_parameters An instance of class RenderingParameters.
 * @param[in] filename The file to write.
 * @throws std::runtime_error if unable to open the given file for writing.
 */
void save_rendering_parameters(RenderingParameters rendering_parameters, std::string filename)
{
	std::ofstream file(filename);
	if (file.fail()) {
		throw std::runtime_error("Error opening file for writing: " + filename);
	}
	cereal::JSONOutputArchive output_archive(file);
	output_archive(cereal::make_nvp("rendering_parameters", rendering_parameters));
};

/**
 * @brief Returns a glm/OpenGL compatible viewport vector that flips y and
 * has the origin on the top-left, like in OpenCV.
 */
glm::vec4 get_opencv_viewport(int width, int height)
{
	return glm::vec4(0, height, width, -height);
};

/**
 * @brief Converts a glm::mat4x4 to a cv::Mat.
 *
 * Note: I think the last use of this function is below in
 * get_3x4_affine_camera_matrix().
 */
cv::Mat to_mat(const glm::mat4x4& glm_matrix)
{
	// glm stores its matrices in col-major order in memory, OpenCV in row-major order.
	// Hence we transpose the glm matrix to flip the memory layout, and then point OpenCV
	// to that location.
	auto glm_matrix_t = glm::transpose(glm_matrix);
	cv::Mat opencv_mat(4, 4, CV_32FC1, &glm_matrix_t[0]);
	// we need to clone because the underlying data of the original goes out of scope
	return opencv_mat.clone();
};

/**
 * @brief Creates a 3x4 affine camera matrix from given fitting parameters. The
 * matrix transforms points directly from model-space to screen-space.
 *
 * This function is mainly used since the linear shape fitting fitting::fit_shape_to_landmarks_linear
 * expects one of these 3x4 affine camera matrices, as well as render::extract_texture.
 */
cv::Mat get_3x4_affine_camera_matrix(fitting::RenderingParameters params, int width, int height)
{
	auto view_model = to_mat(params.get_modelview());
	auto ortho_projection = to_mat(params.get_projection());
	cv::Mat mvp = ortho_projection * view_model;

	glm::vec4 viewport(0, height, width, -height); // flips y, origin top-left, like in OpenCV
	// equivalent to what glm::project's viewport does, but we don't change z and w:
	cv::Mat viewport_mat = (cv::Mat_<float>(4, 4) << viewport[2] / 2.0f, 0.0f,       0.0f, viewport[2] / 2.0f + viewport[0],
												     0.0f,               viewport[3] / 2.0f, 0.0f, viewport[3] / 2.0f + viewport[1],
													 0.0f,               0.0f,               1.0f, 0.0f,
													 0.0f,               0.0f,               0.0f, 1.0f);

	cv::Mat full_projection_4x4 = viewport_mat * mvp;
	cv::Mat full_projection_3x4 = full_projection_4x4.rowRange(0, 3); // we take the first 3 rows, but then set the last one to [0 0 0 1]
	full_projection_3x4.at<float>(2, 0) = 0.0f;
	full_projection_3x4.at<float>(2, 1) = 0.0f;
	full_projection_3x4.at<float>(2, 2) = 0.0f;
	full_projection_3x4.at<float>(2, 3) = 1.0f;

	return full_projection_3x4;
};

	} /* namespace fitting */
} /* namespace eos */

#endif /* RENDERINGPARAMETERS_HPP_ */
<commit_msg>Added explicit conversion from the rotation matrix to quaternion<commit_after>/*
 * eos - A 3D Morphable Model fitting library written in modern C++11/14.
 *
 * File: include/eos/fitting/RenderingParameters.hpp
 *
 * Copyright 2016 Patrik Huber
 *
 * 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.
 */
#pragma once

#ifndef RENDERINGPARAMETERS_HPP_
#define RENDERINGPARAMETERS_HPP_

#include "eos/fitting/orthographic_camera_estimation_linear.hpp"

#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/quaternion.hpp"

#include "eos/fitting/detail/optional_cerealisation.hpp"
#include "eos/fitting/detail/glm_cerealisation.hpp"
#include "cereal/cereal.hpp"
#include "cereal/archives/json.hpp"

#include "opencv2/core/core.hpp"

#include "boost/optional.hpp"

#include <string>
#include <fstream>
#include <stdexcept>

namespace eos {
	namespace fitting {

/**
 * @brief A class representing a camera viewing frustum. At the moment only
 * fully tested with orthographic camera.
 */
struct Frustum
{
//	float l, r, b, t;
	Frustum() {};
	Frustum(float l, float r, float b, float t) : l(l), r(r), b(b), t(t) {};
	//Frustum(float l, float r, float b, float t, float n, float f) : l(l), r(r), b(b), t(t), n(n), f(f) {};
	float l = -1.0f;
	float r = 1.0f;
	float b = -1.0f;
	float t = 1.0f;
	//boost::optional<float> n; // These are not needed yet but probably will in the future,
	//boost::optional<float> f; // and then it's good if the old serialised files stay compatible.

	friend class cereal::access;
	/**
	 * Serialises this class using cereal.
	 *
	 * @param[in] ar The archive to serialise to (or to serialise from).
	 */
	template<class Archive>
	void serialize(Archive& archive)
	{
		archive(CEREAL_NVP(l), CEREAL_NVP(r), CEREAL_NVP(b), CEREAL_NVP(t));
	};
};

enum class CameraType
{
	Orthographic,
	Perspective
};

/**
 * @brief Represents a set of estimated model parameters (rotation, translation) and
 * camera parameters (viewing frustum).
 *
 * The estimated rotation and translation transform the model from model-space to camera-space,
 * and, if one wishes to use OpenGL, can be used to build the model-view matrix.
 * The parameters are the inverse of the camera position in 3D space.
 *
 * The camera frustum describes the size of the viewing plane of the camera, and
 * can be used to build an OpenGL-conformant orthographic projection matrix.
 *
 * Together, these parameters fully describe the imaging process of a given model instance
 * (under an orthographic projection).
 *
 * The rotation values are given in radians and estimated using the RPY convention.
 * Yaw is applied first to the model, then pitch, then roll (R * P * Y * vertex).
 * In general, the convention is as follows:
 * 	 r_x = Pitch
 *	 r_y = Yaw. Positive means subject is looking left (we see her right cheek).
 *	 r_z = Roll. Positive means the subject's right eye is further down than the other one (he tilts his head to the right).
 * However, we're using a quaternion now to represent the rotation, and glm::eulerAngles() will give
 * slightly different angles (according to a different (undocumented)) convention. However, the
 * rotation is exactly the same! (i.e. they are represented by the same quaternion / rotation matrix).
 *
 * This should always represent all parameters necessary to render the model to an image, and be completely OpenGL compliant.
 */
class RenderingParameters
{
public:
	// Creates with default frustum...
	RenderingParameters() {};

	// Initialisation for Eigen::LevMarq
	// This creates the correct rotation quaternion in the case the angles were estimated/given by R*P*Y*v.
	// Angles given in radian.
	// Note: If you subsequently use RP::get_rotation() and glm::eulerAngles() on it, the angles you get out will be slightly different from the ones you put in here.
	// But they will describe the same rotation! Just in a different order. (i.e. the rotation matrix or quaternion for both of these two sets of angles is identical.)
	RenderingParameters(CameraType camera_type, Frustum camera_frustum, float r_x, float r_y, float r_z, float tx, float ty, int screen_width, int screen_height) : camera_type(camera_type), frustum(camera_frustum), t_x(tx), t_y(ty), screen_width(screen_width), screen_height(screen_height) {
		auto rot_mtx_x = glm::rotate(glm::mat4(1.0f), r_x, glm::vec3{ 1.0f, 0.0f, 0.0f });
		auto rot_mtx_y = glm::rotate(glm::mat4(1.0f), r_y, glm::vec3{ 0.0f, 1.0f, 0.0f });
		auto rot_mtx_z = glm::rotate(glm::mat4(1.0f), r_z, glm::vec3{ 0.0f, 0.0f, 1.0f });
		auto zxy_rotation_matrix = rot_mtx_z * rot_mtx_x * rot_mtx_y;
		rotation = glm::quat(zxy_rotation_matrix);
	};

	// This assumes estimate_sop was run on points with OpenCV viewport! I.e. y flipped.
	RenderingParameters(ScaledOrthoProjectionParameters ortho_params, int image_width, int image_height) {
		camera_type = CameraType::Orthographic;
		rotation = glm::quat(ortho_params.R);
		t_x = ortho_params.tx;
		t_y = ortho_params.ty;
		const auto l = 0.0;
		const auto r = image_width / ortho_params.s;
		const auto b = 0.0; // The b and t values are not tested for what happens if the SOP parameters
		const auto t = image_height / ortho_params.s; // were estimated on a non-flipped viewport.
		frustum = Frustum(l, r, b, t);
	};

	glm::quat get_rotation() const {
		return rotation;
	};

	glm::mat4x4 get_modelview() const {
		glm::mat4x4 modelview = glm::mat4_cast(rotation);
		modelview[3][0] = t_x;
		modelview[3][1] = t_y;
		return modelview;
	};

	glm::mat4x4 get_projection() const {
		if (camera_type == CameraType::Orthographic)
		{
			return glm::ortho<float>(frustum.l, frustum.r, frustum.b, frustum.t);
		}
		else {
			throw std::runtime_error("get_projection() for CameraType::Perspective is not implemented yet.");
		}
	};

private:
	CameraType camera_type = CameraType::Orthographic;
	Frustum frustum; // Can construct a glm::ortho or glm::perspective matrix from this.

	glm::quat rotation;

	float t_x;
	float t_y;
	//boost::optional<float> t_z;
	//boost::optional<float> focal_length; // only for certain camera types. Should it go into Frustum?

	int screen_width; // (why) do we need these?
	int screen_height;

	friend class cereal::access;
	/**
	 * Serialises this class using cereal.
	 *
	 * @param[in] ar The archive to serialise to (or to serialise from).
	 */
	template<class Archive>
	void serialize(Archive& archive)
	{
		archive(CEREAL_NVP(camera_type), CEREAL_NVP(frustum), CEREAL_NVP(rotation), CEREAL_NVP(t_x), CEREAL_NVP(t_y), CEREAL_NVP(screen_width), CEREAL_NVP(screen_height));
	};
};

/**
 * Saves the rendering parameters for an image to a json file.
 *
 * @param[in] rendering_parameters An instance of class RenderingParameters.
 * @param[in] filename The file to write.
 * @throws std::runtime_error if unable to open the given file for writing.
 */
void save_rendering_parameters(RenderingParameters rendering_parameters, std::string filename)
{
	std::ofstream file(filename);
	if (file.fail()) {
		throw std::runtime_error("Error opening file for writing: " + filename);
	}
	cereal::JSONOutputArchive output_archive(file);
	output_archive(cereal::make_nvp("rendering_parameters", rendering_parameters));
};

/**
 * @brief Returns a glm/OpenGL compatible viewport vector that flips y and
 * has the origin on the top-left, like in OpenCV.
 */
glm::vec4 get_opencv_viewport(int width, int height)
{
	return glm::vec4(0, height, width, -height);
};

/**
 * @brief Converts a glm::mat4x4 to a cv::Mat.
 *
 * Note: I think the last use of this function is below in
 * get_3x4_affine_camera_matrix().
 */
cv::Mat to_mat(const glm::mat4x4& glm_matrix)
{
	// glm stores its matrices in col-major order in memory, OpenCV in row-major order.
	// Hence we transpose the glm matrix to flip the memory layout, and then point OpenCV
	// to that location.
	auto glm_matrix_t = glm::transpose(glm_matrix);
	cv::Mat opencv_mat(4, 4, CV_32FC1, &glm_matrix_t[0]);
	// we need to clone because the underlying data of the original goes out of scope
	return opencv_mat.clone();
};

/**
 * @brief Creates a 3x4 affine camera matrix from given fitting parameters. The
 * matrix transforms points directly from model-space to screen-space.
 *
 * This function is mainly used since the linear shape fitting fitting::fit_shape_to_landmarks_linear
 * expects one of these 3x4 affine camera matrices, as well as render::extract_texture.
 */
cv::Mat get_3x4_affine_camera_matrix(fitting::RenderingParameters params, int width, int height)
{
	auto view_model = to_mat(params.get_modelview());
	auto ortho_projection = to_mat(params.get_projection());
	cv::Mat mvp = ortho_projection * view_model;

	glm::vec4 viewport(0, height, width, -height); // flips y, origin top-left, like in OpenCV
	// equivalent to what glm::project's viewport does, but we don't change z and w:
	cv::Mat viewport_mat = (cv::Mat_<float>(4, 4) << viewport[2] / 2.0f, 0.0f,       0.0f, viewport[2] / 2.0f + viewport[0],
												     0.0f,               viewport[3] / 2.0f, 0.0f, viewport[3] / 2.0f + viewport[1],
													 0.0f,               0.0f,               1.0f, 0.0f,
													 0.0f,               0.0f,               0.0f, 1.0f);

	cv::Mat full_projection_4x4 = viewport_mat * mvp;
	cv::Mat full_projection_3x4 = full_projection_4x4.rowRange(0, 3); // we take the first 3 rows, but then set the last one to [0 0 0 1]
	full_projection_3x4.at<float>(2, 0) = 0.0f;
	full_projection_3x4.at<float>(2, 1) = 0.0f;
	full_projection_3x4.at<float>(2, 2) = 0.0f;
	full_projection_3x4.at<float>(2, 3) = 1.0f;

	return full_projection_3x4;
};

	} /* namespace fitting */
} /* namespace eos */

#endif /* RENDERINGPARAMETERS_HPP_ */
<|endoftext|>


<commit_before>#include "TTModular.h"

#include <iostream>
#include <string>

// A class for our application
class DemoApp {

public:

    DemoApp(){};
    ~DemoApp(){};

    // This application is divided into four main functions
    void Setup();
    void Export();
    void Execute(std::string command);
    void Quit();

private:

    // Declare the application manager, our application and another one
    TTObject mApplicationManager;
    TTObject mApplicationDemo;
    TTObject mApplicationRemote;

    // Declare protocol units to use
    TTObject mProtocolMinuit;
    TTObject mProtocolWebSocket;

public:

    // Declare publicly all datas of our application to retreive them from the callback function
    TTObject mDataDemoParameter;     // a parameter is relative to the state of our application
    TTObject mDataDemoMessage;       // a message is a kind of command to send to our application
    TTObject mDataDemoReturn;        // a return is a kind of notification sent by our application

    // Be friend with the callback function
    friend TTErr DemoAppDataReturnValueCallback(const TTValue& baton, const TTValue& v);
};

// Callback function to get data's value back
TTErr DemoAppDataReturnValueCallback(const TTValue& baton, const TTValue& v);

int
main(int argc, char **argv)
{
    DemoApp app;

    TTLogMessage("\n*** Start of Jamoma Modular demonstration ***\n");

    app.Setup();

    // read command from console
    do {
        TTLogMessage("\nType a command : \n");

        std::string s;
        std::getline(std::cin, s);

        // quit the application
        if (!s.compare("quit")) {

            app.Quit();

            TTLogMessage("\n*** End of Jamoma Modular demonstration ***\n");
            return EXIT_SUCCESS;
        }
        // dump informations about the application
        else if (!s.compare("export")) {

             app.Export();
        }
        // parse a command and execute it
        else {

            app.Execute(s);
        }
    }
    while (YES);
}

void
DemoApp::Setup()
{
    TTValue     args, v, out, none;
    TTAddress   address;
    TTErr       err;

    TTLogMessage("\n*** Initialisation of Modular environnement ***\n");
    /////////////////////////////////////////////////////////////////////

    // Init the Modular library (passing the folder path where all the dylibs are)
    TTModularInit("/usr/local/jamoma");

    // Create an application manager
    mApplicationManager = TTObject("ApplicationManager");

    TTLogMessage("\n*** Creation of myDemoApp and myRemoteApp applications ***\n");
    ////////////////////////////////////////////////////////////////////////////////

    // Create a local application called "demo" and get it back
    err = mApplicationManager.send("ApplicationInstantiateLocal", "demo", out);

    if (err) {
        TTLogError("Error : can't create myDemoApp application \n");
        return;
    }
    else
        mApplicationDemo = out[0];

    // Create a distant application called "i-score" and get it back
    err = mApplicationManager.send("ApplicationInstantiateDistant", "i-score", out);

    if (err) {
        TTLogError("Error : can't create myRemoteApp application \n");
        return;
    }
    else
        mApplicationRemote = out[0];

    // Get registered application names
    mApplicationManager.get("applicationNames", out);
    for (TTElementIter it = out.begin() ; it != out.end() ; it++) {
        TTSymbol name = TTElement(*it);
        TTLogMessage("%s application is well registered into the application manager \n", name.c_str());
    }

    TTLogMessage("\n*** Enable Minuit communication ***\n");
    ////////////////////////////////////////////////////////////////////////

    // Create a Minuit protocol unit
    err = mApplicationManager.send("ProtocolInstantiate", "Minuit", out);

    if (err) {
        TTLogError("Error : can't create Minuit protocol unit \n");
        return;
    }
    else
        mProtocolMinuit = out[0];

    // Get Minuit Protocol attribute names and types
    mProtocolMinuit.get("parameterNames", out);
    for (TTElementIter it = out.begin() ; it != out.end() ; it++) {
        TTSymbol name = TTElement(*it);
        TTSymbol type = mProtocolMinuit.attributeType(name);
        TTLogMessage("Minuit %s parameter is a %s \n", name.c_str(), type.c_str());
    }

    // Register myDemoApp and myRemoteApp to the Minuit protocol
    mProtocolMinuit.send("ApplicationRegister", "demo", out);
    mProtocolMinuit.send("ApplicationRegister", "i-score", out);

    // Select myDemoApp to set its protocol parameters
    mProtocolMinuit.send("ApplicationSelect", "demo", out);
    mProtocolMinuit.set("port", 9998);
    mProtocolMinuit.set("ip", "127.0.0.1");

    // Select myRemoteApp to set its protocol parameters
    mProtocolMinuit.send("ApplicationSelect", "i-score", out);
    mProtocolMinuit.set("port", 13579);
    mProtocolMinuit.set("ip", "127.0.0.1");

    // Get Minuit parameters for each registered application
    mProtocolMinuit.get("applicationNames", out);
    for (TTElementIter it = out.begin() ; it != out.end() ; it++) {
        TTSymbol name = TTElement(*it);

        mProtocolMinuit.send("ApplicationSelect", name, out);
        TTLogMessage("Minuit setup for %s application : \n", name.c_str());

        mProtocolMinuit.get("ip", v);
        TTSymbol ip = v[0];
        TTLogMessage("- ip = %s \n", ip.c_str());

        mProtocolMinuit.get("port", v);
        TTUInt16 port = v[0];
        TTLogMessage("- port = %d \n", port);
    }

    // Enable Minuit communication
    mProtocolMinuit.send("Run");

/*
    TTLogMessage("\n*** Enable WebSocket communication ***\n");
    ////////////////////////////////////////////////////////////////////////

    // Create a WebSocket protocol unit
    err = mApplicationManager.send("ProtocolInstantiate", "WebSocket", out);

    if (err) {
        TTLogError("Error : can't create WebSocket protocol unit \n");
        return;
    }
    else
        mProtocolWebSocket = out[0];

    // Get WebSocket Protocol attribute names and types
    mProtocolMinuit.get("parameterNames", out);
    for (TTElementIter it = out.begin() ; it != out.end() ; it++) {
        TTSymbol name = TTElement(*it);
        TTLogMessage("WebSocket::%s is a %s \n", name.c_str(), mProtocolWebSocket.attributeType(name).c_str());
    }

    // Register myDemoApp and myRemoteApp to the WebSocket protocol
    mProtocolWebSocket.send("ApplicationRegister", "demo", out);
    mProtocolWebSocket.send("ApplicationRegister", "i-score", out);

    // Select myDemoApp to set its protocol parameters
    mProtocolWebSocket.send("ApplicationSelect", "demo", out);
    mProtocolWebSocket.set("???", none);

    // Select myRemoteApp to set its protocol parameters
    mProtocolWebSocket.send("ApplicationSelect", "i-score", out);
    mProtocolWebSocket.set("???", none);

    // Enable WebSocket communication
    mProtocolWebSocket.send("Run");
*/

    TTLogMessage("\n*** Current Protocol Setup ***\n");
    // Get protocol names
    mApplicationManager.get("protocolNames", out);
    for (TTElementIter it = out.begin() ; it != out.end() ; it++) {
        TTSymbol name = TTElement(*it);
        TTLogMessage("%s protocol is well registered into the application manager \n", name.c_str());
    }

	TTLogMessage("\n*** Creation of myDemoApp datas ***\n");
    /////////////////////////////////////////////////////////

    // Create a parameter data and set its callback function and baton and some attributes
    mDataDemoParameter = TTObject("Data", "parameter");

    // Setup the callback mechanism to get the value back
    args = TTValue(TTPtr(this), mDataDemoParameter);
    mDataDemoParameter.set("baton", args);
    mDataDemoParameter.set("function", TTPtr(&DemoAppDataReturnValueCallback));

    // Setup the data attributes depending of its use inside the application
    mDataDemoParameter.set("type", "decimal");
    mDataDemoParameter.set("rangeBounds", TTValue(-1., 1.));
    mDataDemoParameter.set("rangeClipmode", "both");
    mDataDemoParameter.set("rampDrive", "System");
    mDataDemoParameter.set("description", "this parameter is useful for demo purpose");

    // Register the parameter data into myDemoApp at an address
    args = TTValue("/myParameter", mDataDemoParameter);
    err = mApplicationDemo.send("ObjectRegister", args, out);

    if (err)
        TTLogError("Error : can't register data at /myParameter address \n");

    else {
        address = out[0];
        TTLogMessage("\n /myParameter : effective registration address is %s \n", address.c_str());
    }

    // Create a message data and set its callback function and baton and some attributes
    mDataDemoMessage = TTObject("Data", "message");

    // Setup the callback mechanism to get the value back
    args = TTValue(TTPtr(this), mDataDemoMessage);
    mDataDemoMessage.set("baton", args);
    mDataDemoMessage.set("function", TTPtr(&DemoAppDataReturnValueCallback));

    // Setup the data attributes depending of its use inside the application
    mDataDemoMessage.set("type", "none");
    mDataDemoMessage.set("description", "this message is useful for demo purpose");

    // Register the message data into myDemoApp at an address
    args = TTValue("/myMessage", mDataDemoMessage);
    mApplicationDemo.send("ObjectRegister", args, out);

    if (err)
        TTLogError("Error : can't register data at /myMessage address \n");

    else {
        address = out[0];
        TTLogMessage("\n /myMessage : effective registration address is %s \n", address.c_str());
    }

    // Create a return data and set its callback function and baton and some attributes
    mDataDemoReturn = TTObject("Data", "return");

    // Setup the callback mechanism to get the value back
    args = TTValue(TTPtr(this), mDataDemoReturn);
    mDataDemoReturn.set("baton", args);
    mDataDemoReturn.set("function", TTPtr(&DemoAppDataReturnValueCallback));

    // Setup the data attributes depending of its use inside the application
    mDataDemoReturn.set("type", "integer");
    mDataDemoReturn.set("description", "this return is useful for demo purpose");

    // Register the return data into myDemoApp at an address
    args = TTValue("/myReturn", mDataDemoReturn);
    mApplicationDemo.send("ObjectRegister", args, out);

    if (err)
        TTLogError("Error : can't register data at /myReturn address \n");

    else {
        address = out[0];
        TTLogMessage("\n /myReturn : effective registration address is %s \n", address.c_str());
    }
}

void
DemoApp::Export()
{
    TTValue     out;
    TTObject    xmlHandler("XmlHandler");

    // export the namespace of myDemoApp
    xmlHandler.set("object", mApplicationDemo);
    xmlHandler.send("Write", "./myDemoApp.xml", out);
}

void
DemoApp::Execute(std::string command)
{
    // parse the command : address value
    TTValue v = TTString(command);
    v.fromString();

    // a command have to start by a symbol
    if (v.size() > 1) {

        if (v[0].type() == kTypeSymbol) {

            TTSymbol    address = v[0];
            TTValue     args, out, none;

            args.copyFrom(v, 1);

            // Retreive a data object
            TTErr err = mApplicationDemo.send("ObjectRetreive", address, out);

            if (!err) {

                TTObject aData = out[0];

                // Set data's value and check his validity
                aData.send("Command", args, none);
            }
        }
    }
}

void
DemoApp::Quit()
{
    TTValue out;

    TTLogMessage("\n*** Release myDemoApp datas ***\n");
    /////////////////////////////////////////////////////

    // Unregister the parameter
    if ( mApplicationDemo.send("ObjectUnregister", "/myParameter", out))
        TTLogError("Error : can't unregister data at /myParameter address \n");

    // Unregister the message
    if (mApplicationDemo.send("ObjectUnregister", "/myMessage", out))
        TTLogError("Error : can't unregister data at /myMessage address \n");

    // Unregister the return
    if (mApplicationDemo.send("ObjectUnregister", "/myReturn", out))
        TTLogError("Error : can't unregister data at /myReturn address \n");

    TTLogMessage("\n*** Release protocols ***\n");
    ///////////////////////////////////////////////

    mApplicationManager.send("ProtocolRelease", "Minuit", out);
    //mApplicationManager.send("ProtocolRelease", "WebSocket", out);

    TTLogMessage("\n*** Release applications ***\n");
    //////////////////////////////////////////////////

    mApplicationManager.send("ApplicationRelease", "i-score", out);
    mApplicationManager.send("ApplicationRelease", "demo", out);
}

TTErr
DemoAppDataReturnValueCallback(const TTValue& baton, const TTValue& value)
{
    DemoApp*    demoApp = (DemoApp*)TTPtr(baton[0]);
    TTObject    anObject = baton[1];

	// Reteive which data has been updated
    if (anObject.instance() == demoApp->mDataDemoParameter.instance()) {

        // print the returned value
        TTLogMessage("/myParameter has been updated to %s \n", value.toString().data());
        return kTTErrNone;
    }

    if (anObject.instance() == demoApp->mDataDemoMessage.instance()) {

        // print the returned value
        TTLogMessage("/myMessage has been updated to %s \n", value.toString().data());
        return kTTErrNone;
    }

    if (anObject.instance() == demoApp->mDataDemoReturn.instance()) {

        // print the returned value
        TTLogMessage("/myReturn has been updated to %s \n", value.toString().data());
        return kTTErrNone;
    }

    return kTTErrGeneric;
}<commit_msg>minor<commit_after>#include "TTModular.h"

#include <iostream>
#include <string>

// A class for our application
class DemoApp {

public:

    DemoApp(){};
    ~DemoApp(){};

    // This application is divided into four main functions
    void Setup();
    void Export();
    void Execute(std::string command);
    void Quit();

private:

    // Declare the application manager, our application and another one
    TTObject mApplicationManager;
    TTObject mApplicationDemo;
    TTObject mApplicationRemote;

    // Declare protocol units to use
    TTObject mProtocolMinuit;
    TTObject mProtocolWebSocket;

public:

    // Declare publicly all datas of our application to retreive them from the callback function
    TTObject mDataDemoParameter;     // a parameter is relative to the state of our application
    TTObject mDataDemoMessage;       // a message is a kind of command to send to our application
    TTObject mDataDemoReturn;        // a return is a kind of notification sent by our application

    // Be friend with the callback function
    friend TTErr DemoAppDataReturnValueCallback(const TTValue& baton, const TTValue& v);
};

// Callback function to get data's value back
TTErr DemoAppDataReturnValueCallback(const TTValue& baton, const TTValue& v);

int
main(int argc, char **argv)
{
    DemoApp app;

    TTLogMessage("\n*** Start of Jamoma Modular demonstration ***\n");

    app.Setup();

    // read command from console
    do {
        TTLogMessage("\nType a command : \n");

        std::string s;
        std::getline(std::cin, s);

        // quit the application
        if (!s.compare("quit")) {

            app.Quit();

            TTLogMessage("\n*** End of Jamoma Modular demonstration ***\n");
            return EXIT_SUCCESS;
        }
        // dump informations about the application
        else if (!s.compare("export")) {

             app.Export();
        }
        // parse a command and execute it
        else {

            app.Execute(s);
        }
    }
    while (YES);
}

void
DemoApp::Setup()
{
    TTValue     args, v, out, none;
    TTAddress   address;
    TTErr       err;

    TTLogMessage("\n*** Initialisation of Modular environnement ***\n");
    /////////////////////////////////////////////////////////////////////

    // Init the Modular library (passing the folder path where all the dylibs are)
    TTModularInit("/usr/local/jamoma");

    // Create an application manager
    mApplicationManager = TTObject("ApplicationManager");

    TTLogMessage("\n*** Creation of myDemoApp and myRemoteApp applications ***\n");
    ////////////////////////////////////////////////////////////////////////////////

    // Create a local application called "demo" and get it back
    err = mApplicationManager.send("ApplicationInstantiateLocal", "demo", out);

    if (err) {
        TTLogError("Error : can't create myDemoApp application \n");
        return;
    }
    else
        mApplicationDemo = out[0];

    // Create a distant application called "i-score" and get it back
    err = mApplicationManager.send("ApplicationInstantiateDistant", "i-score", out);

    if (err) {
        TTLogError("Error : can't create myRemoteApp application \n");
        return;
    }
    else
        mApplicationRemote = out[0];

    // Get registered application names
    mApplicationManager.get("applicationNames", out);
    for (TTElementIter it = out.begin() ; it != out.end() ; it++) {
        TTSymbol name = TTElement(*it);
        TTLogMessage("%s application is well registered into the application manager \n", name.c_str());
    }

    TTLogMessage("\n*** Enable Minuit communication ***\n");
    ////////////////////////////////////////////////////////////////////////

    // Create a Minuit protocol unit
    err = mApplicationManager.send("ProtocolInstantiate", "Minuit", out);

    if (err) {
        TTLogError("Error : can't create Minuit protocol unit \n");
        return;
    }
    else
        mProtocolMinuit = out[0];

    // Get Minuit Protocol attribute names and types
    mProtocolMinuit.get("parameterNames", out);
    for (TTElementIter it = out.begin() ; it != out.end() ; it++) {
        TTSymbol name = TTElement(*it);
        TTSymbol type = mProtocolMinuit.attributeType(name);
        TTLogMessage("Minuit %s parameter is a %s \n", name.c_str(), type.c_str());
    }

    // Register myDemoApp and myRemoteApp to the Minuit protocol
    mProtocolMinuit.send("ApplicationRegister", "demo", out);
    mProtocolMinuit.send("ApplicationRegister", "i-score", out);

    // Select myDemoApp to set its protocol parameters
    mProtocolMinuit.send("ApplicationSelect", "demo", out);
    mProtocolMinuit.set("port", 9998);
    mProtocolMinuit.set("ip", "127.0.0.1");

    // Select myRemoteApp to set its protocol parameters
    mProtocolMinuit.send("ApplicationSelect", "i-score", out);
    mProtocolMinuit.set("port", 13579);
    mProtocolMinuit.set("ip", "127.0.0.1");

    // Get Minuit parameters for each registered application
    mProtocolMinuit.get("applicationNames", out);
    for (TTElementIter it = out.begin() ; it != out.end() ; it++) {
        TTSymbol name = TTElement(*it);

        mProtocolMinuit.send("ApplicationSelect", name, out);
        TTLogMessage("Minuit setup for %s application : \n", name.c_str());

        mProtocolMinuit.get("ip", v);
        TTSymbol ip = v[0];
        TTLogMessage("- ip = %s \n", ip.c_str());

        mProtocolMinuit.get("port", v);
        TTUInt16 port = v[0];
        TTLogMessage("- port = %d \n", port);
    }

    // Enable Minuit communication
    mProtocolMinuit.send("Run");

/*
    TTLogMessage("\n*** Enable WebSocket communication ***\n");
    ////////////////////////////////////////////////////////////////////////

    // Create a WebSocket protocol unit
    err = mApplicationManager.send("ProtocolInstantiate", "WebSocket", out);

    if (err) {
        TTLogError("Error : can't create WebSocket protocol unit \n");
        return;
    }
    else
        mProtocolWebSocket = out[0];

    // Get WebSocket Protocol attribute names and types
    mProtocolMinuit.get("parameterNames", out);
    for (TTElementIter it = out.begin() ; it != out.end() ; it++) {
        TTSymbol name = TTElement(*it);
        TTLogMessage("WebSocket::%s is a %s \n", name.c_str(), mProtocolWebSocket.attributeType(name).c_str());
    }

    // Register myDemoApp and myRemoteApp to the WebSocket protocol
    mProtocolWebSocket.send("ApplicationRegister", "demo", out);
    mProtocolWebSocket.send("ApplicationRegister", "i-score", out);

    // Select myDemoApp to set its protocol parameters
    mProtocolWebSocket.send("ApplicationSelect", "demo", out);
    mProtocolWebSocket.set("???", none);

    // Select myRemoteApp to set its protocol parameters
    mProtocolWebSocket.send("ApplicationSelect", "i-score", out);
    mProtocolWebSocket.set("???", none);

    // Enable WebSocket communication
    mProtocolWebSocket.send("Run");
*/

    TTLogMessage("\n*** Current Protocol Setup ***\n");
    // Get protocol names
    mApplicationManager.get("protocolNames", out);
    for (TTElementIter it = out.begin() ; it != out.end() ; it++) {
        TTSymbol name = TTElement(*it);
        TTLogMessage("%s protocol is well registered into the application manager \n", name.c_str());
    }

	TTLogMessage("\n*** Creation of myDemoApp datas ***\n");
    /////////////////////////////////////////////////////////

    // Create a parameter data and set its callback function and baton and some attributes
    mDataDemoParameter = TTObject("Data", "parameter");

    // Setup the callback mechanism to get the value back
    args = TTValue(TTPtr(this), mDataDemoParameter);
    mDataDemoParameter.set("baton", args);
    mDataDemoParameter.set("function", TTPtr(&DemoAppDataReturnValueCallback));

    // Setup the data attributes depending of its use inside the application
    mDataDemoParameter.set("type", "decimal");
    mDataDemoParameter.set("rangeBounds", TTValue(-1., 1.));
    mDataDemoParameter.set("rangeClipmode", "both");
    mDataDemoParameter.set("rampDrive", "System");
    mDataDemoParameter.set("description", "this parameter is useful for demo purpose");

    // Register the parameter data into myDemoApp at an address
    args = TTValue("/myParameter", mDataDemoParameter);
    err = mApplicationDemo.send("ObjectRegister", args, out);

    if (err)
        TTLogError("Error : can't register data at /myParameter address \n");

    else {
        address = out[0];
        TTLogMessage("\n /myParameter : effective registration address is %s \n", address.c_str());
    }

    // Create a message data and set its callback function and baton and some attributes
    mDataDemoMessage = TTObject("Data", "message");

    // Setup the callback mechanism to get the value back
    args = TTValue(TTPtr(this), mDataDemoMessage);
    mDataDemoMessage.set("baton", args);
    mDataDemoMessage.set("function", TTPtr(&DemoAppDataReturnValueCallback));

    // Setup the data attributes depending of its use inside the application
    mDataDemoMessage.set("type", "none");
    mDataDemoMessage.set("description", "this message is useful for demo purpose");

    // Register the message data into myDemoApp at an address
    args = TTValue("/myMessage", mDataDemoMessage);
    mApplicationDemo.send("ObjectRegister", args, out);

    if (err)
        TTLogError("Error : can't register data at /myMessage address \n");

    else {
        address = out[0];
        TTLogMessage("\n /myMessage : effective registration address is %s \n", address.c_str());
    }

    // Create a return data and set its callback function and baton and some attributes
    mDataDemoReturn = TTObject("Data", "return");

    // Setup the callback mechanism to get the value back
    args = TTValue(TTPtr(this), mDataDemoReturn);
    mDataDemoReturn.set("baton", args);
    mDataDemoReturn.set("function", TTPtr(&DemoAppDataReturnValueCallback));

    // Setup the data attributes depending of its use inside the application
    mDataDemoReturn.set("type", "integer");
    mDataDemoReturn.set("description", "this return is useful for demo purpose");

    // Register the return data into myDemoApp at an address
    args = TTValue("/myReturn", mDataDemoReturn);
    mApplicationDemo.send("ObjectRegister", args, out);

    if (err)
        TTLogError("Error : can't register data at /myReturn address \n");

    else {
        address = out[0];
        TTLogMessage("\n /myReturn : effective registration address is %s \n", address.c_str());
    }
}

void
DemoApp::Export()
{
    TTValue     out;
    TTObject    xmlHandler("XmlHandler");

    // export the namespace of myDemoApp
    xmlHandler.set("object", mApplicationDemo);
    xmlHandler.send("Write", "./myDemoApp.xml", out);
}

void
DemoApp::Execute(std::string command)
{
    // parse the command : address value
    TTValue v = TTString(command);
    v.fromString();

    // a command has to start with a symbol
    if (v.size() > 1) {

        if (v[0].type() == kTypeSymbol) {

            TTSymbol    address = v[0];
            TTValue     args, out, none;

            args.copyFrom(v, 1);

            // Retreive a data object
            TTErr err = mApplicationDemo.send("ObjectRetreive", address, out);

            if (!err) {

                TTObject aData = out[0];

                // Set data's value and check his validity
                aData.send("Command", args, none);
            }
        }
    }
}

void
DemoApp::Quit()
{
    TTValue out;

    TTLogMessage("\n*** Release myDemoApp datas ***\n");
    /////////////////////////////////////////////////////

    // Unregister the parameter
    if ( mApplicationDemo.send("ObjectUnregister", "/myParameter", out))
        TTLogError("Error : can't unregister data at /myParameter address \n");

    // Unregister the message
    if (mApplicationDemo.send("ObjectUnregister", "/myMessage", out))
        TTLogError("Error : can't unregister data at /myMessage address \n");

    // Unregister the return
    if (mApplicationDemo.send("ObjectUnregister", "/myReturn", out))
        TTLogError("Error : can't unregister data at /myReturn address \n");

    TTLogMessage("\n*** Release protocols ***\n");
    ///////////////////////////////////////////////

    mApplicationManager.send("ProtocolRelease", "Minuit", out);
    //mApplicationManager.send("ProtocolRelease", "WebSocket", out);

    TTLogMessage("\n*** Release applications ***\n");
    //////////////////////////////////////////////////

    mApplicationManager.send("ApplicationRelease", "i-score", out);
    mApplicationManager.send("ApplicationRelease", "demo", out);
}

TTErr
DemoAppDataReturnValueCallback(const TTValue& baton, const TTValue& value)
{
    DemoApp*    demoApp = (DemoApp*)TTPtr(baton[0]);
    TTObject    anObject = baton[1];

	// Reteive which data has been updated
    if (anObject.instance() == demoApp->mDataDemoParameter.instance()) {

        // print the returned value
        TTLogMessage("/myParameter has been updated to %s \n", value.toString().data());
        return kTTErrNone;
    }

    if (anObject.instance() == demoApp->mDataDemoMessage.instance()) {

        // print the returned value
        TTLogMessage("/myMessage has been updated to %s \n", value.toString().data());
        return kTTErrNone;
    }

    if (anObject.instance() == demoApp->mDataDemoReturn.instance()) {

        // print the returned value
        TTLogMessage("/myReturn has been updated to %s \n", value.toString().data());
        return kTTErrNone;
    }

    return kTTErrGeneric;
}<|endoftext|>