<commit_before>/*
   Copyright (c) 2009-2014, Jack Poulson
   All rights reserved.

   This file is part of Elemental and is under the BSD 2-Clause License,
   which can be found in the LICENSE file in the root directory, or at
   http://opensource.org/licenses/BSD-2-Clause
*/
#include "El.hpp"

namespace El {

template<typename T>
void EntrywiseMap( Matrix<T>& A, std::function<T(T)> func )
{
    DEBUG_ONLY(CallStackEntry cse("EntrywiseMap"))
    const Int m = A.Height();
    const Int n = A.Width();
    for( Int j=0; j<n; ++j )
        for( Int i=0; i<m; ++i )
            A.Set( i, j, func(A.Get(i,j)) );
}

template<typename T>
void EntrywiseMap( AbstractDistMatrix<T>& A, std::function<T(T)> func )
{ EntrywiseMap( A.Matrix(), func ); }

template<typename T>
void EntrywiseMap( AbstractBlockDistMatrix<T>& A, std::function<T(T)> func )
{ EntrywiseMap( A.Matrix(), func ); }

template<typename S,typename T>
void EntrywiseMap( const Matrix<S>& A, Matrix<T>& B, std::function<T(S)> func )
{
    DEBUG_ONLY(CallStackEntry cse("EntrywiseMap"))
    const Int m = A.Height();
    const Int n = A.Width();
    B.Resize( m, n );
    for( Int j=0; j<n; ++j )
        for( Int i=0; i<m; ++i )
            B.Set( i, j, func(A.Get(i,j)) );
}

template<typename S,typename T>
void EntrywiseMap
( const AbstractDistMatrix<S>& A, AbstractDistMatrix<T>& B,
  std::function<T(S)> func )
{
    B.AlignWith( A.DistData() );
    B.Resize( A.Height(), A.Width() );
    EntrywiseMap( A.LockedMatrix(), B.Matrix(), func );
}

template<typename S,typename T>
void EntrywiseMap
( const AbstractBlockDistMatrix<S>& A, AbstractBlockDistMatrix<T>& B,
  std::function<T(S)> func )
{
    B.AlignWith( A.DistData() );
    B.Resize( A.Height(), A.Width() );
    EntrywiseMap( A.LockedMatrix(), B.Matrix(), func );
}

#define PROTO(T) \
  template void EntrywiseMap( Matrix<T>& A, std::function<T(T)> func ); \
  template void EntrywiseMap \
  ( AbstractDistMatrix<T>& A, std::function<T(T)> func ); \
  template void EntrywiseMap \
  ( AbstractBlockDistMatrix<T>& A, std::function<T(T)> func );

#define PROTO_TYPES(S,T) \
  template void EntrywiseMap \
  ( const Matrix<S>& A, Matrix<T>& B, std::function<T(S)> func ); \
  template void EntrywiseMap \
  ( const AbstractDistMatrix<S>& A, AbstractDistMatrix<T>& B, \
    std::function<T(S)> func ); \
  template void EntrywiseMap \
  ( const AbstractBlockDistMatrix<S>& A, AbstractBlockDistMatrix<T>& B, \
    std::function<T(S)> func );

#define PROTO_INT(T) \
  PROTO(T) \
  PROTO_TYPES(T,T)

#define PROTO_REAL(T) \
  PROTO(T) \
  PROTO_TYPES(Int,T) \
  PROTO_TYPES(T,T)

#define PROTO_COMPLEX(T) \
  PROTO(T) \
  PROTO_TYPES(Int,T) \
  PROTO_TYPES(Base<T>,T)

#include "El/macros/Instantiate.h"

} // namespace El
<commit_msg>Generalizing EntrywiseMap function to better support recent Copy and Proxy extensions<commit_after>/*
   Copyright (c) 2009-2014, Jack Poulson
   All rights reserved.

   This file is part of Elemental and is under the BSD 2-Clause License,
   which can be found in the LICENSE file in the root directory, or at
   http://opensource.org/licenses/BSD-2-Clause
*/
#include "El.hpp"

namespace El {

template<typename T>
void EntrywiseMap( Matrix<T>& A, std::function<T(T)> func )
{
    DEBUG_ONLY(CallStackEntry cse("EntrywiseMap"))
    const Int m = A.Height();
    const Int n = A.Width();
    for( Int j=0; j<n; ++j )
        for( Int i=0; i<m; ++i )
            A.Set( i, j, func(A.Get(i,j)) );
}

template<typename T>
void EntrywiseMap( AbstractDistMatrix<T>& A, std::function<T(T)> func )
{ EntrywiseMap( A.Matrix(), func ); }

template<typename T>
void EntrywiseMap( AbstractBlockDistMatrix<T>& A, std::function<T(T)> func )
{ EntrywiseMap( A.Matrix(), func ); }

template<typename S,typename T>
void EntrywiseMap( const Matrix<S>& A, Matrix<T>& B, std::function<T(S)> func )
{
    DEBUG_ONLY(CallStackEntry cse("EntrywiseMap"))
    const Int m = A.Height();
    const Int n = A.Width();
    B.Resize( m, n );
    for( Int j=0; j<n; ++j )
        for( Int i=0; i<m; ++i )
            B.Set( i, j, func(A.Get(i,j)) );
}

template<typename S,typename T>
void EntrywiseMap
( const AbstractDistMatrix<S>& A, AbstractDistMatrix<T>& B,
  std::function<T(S)> func )
{
    B.AlignWith( A.DistData() );
    B.Resize( A.Height(), A.Width() );
    EntrywiseMap( A.LockedMatrix(), B.Matrix(), func );
}

template<typename S,typename T>
void EntrywiseMap
( const AbstractBlockDistMatrix<S>& A, AbstractBlockDistMatrix<T>& B,
  std::function<T(S)> func )
{
    B.AlignWith( A.DistData() );
    B.Resize( A.Height(), A.Width() );
    EntrywiseMap( A.LockedMatrix(), B.Matrix(), func );
}

#define PROTO(T) \
  template void EntrywiseMap( Matrix<T>& A, std::function<T(T)> func ); \
  template void EntrywiseMap \
  ( AbstractDistMatrix<T>& A, std::function<T(T)> func ); \
  template void EntrywiseMap \
  ( AbstractBlockDistMatrix<T>& A, std::function<T(T)> func );

#define PROTO_TYPES(S,T) \
  template void EntrywiseMap \
  ( const Matrix<S>& A, Matrix<T>& B, std::function<T(S)> func ); \
  template void EntrywiseMap \
  ( const AbstractDistMatrix<S>& A, AbstractDistMatrix<T>& B, \
    std::function<T(S)> func ); \
  template void EntrywiseMap \
  ( const AbstractBlockDistMatrix<S>& A, AbstractBlockDistMatrix<T>& B, \
    std::function<T(S)> func );

#define PROTO_INT(T) \
  PROTO(T) \
  PROTO_TYPES(T,T)

#define PROTO_REAL(T) \
  PROTO(T) \
  PROTO_TYPES(Int,T) \
  PROTO_TYPES(T,T)

#define PROTO_FLOAT \
  PROTO_REAL(float) \
  PROTO_TYPES(float,double) \
  PROTO_TYPES(float,Complex<double>)

#define PROTO_DOUBLE \
  PROTO_REAL(double) \
  PROTO_TYPES(double,float) \
  PROTO_TYPES(double,Complex<float>)

#define PROTO_COMPLEX(T) \
  PROTO(T) \
  PROTO_TYPES(Int,T) \
  PROTO_TYPES(Base<T>,T)

#define PROTO_COMPLEX_FLOAT \
  PROTO_COMPLEX(Complex<float>) \
  PROTO_TYPES(Complex<float>,Complex<double>)

#define PROTO_COMPLEX_DOUBLE \
  PROTO_COMPLEX(Complex<double>) \
  PROTO_TYPES(Complex<double>,Complex<float>)

#include "El/macros/Instantiate.h"

} // namespace El
<|endoftext|>


<commit_before>// Copyright (c) 2012 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 "net_disk_cache_remover.h"

#include "base/bind_helpers.h"
#include "base/synchronization/waitable_event.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "net/disk_cache/disk_cache.h"
#include "net/http/http_cache.h"
#include "net/http/http_transaction_factory.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_context.h"
#include "net/base/completion_callback.h"

using content::BrowserThread;
using disk_cache::Backend;
using net::CompletionCallback;
using net::URLRequestContextGetter;

namespace {
// Everything is called and accessed on the IO thread.

void Noop(base::WaitableEvent* completion, int rv) {
  DCHECK(rv == net::OK);
  if (completion)
    completion->Signal();
}

void CallDoomAllEntries(Backend** backend, base::WaitableEvent* completion, int rv) {
  DCHECK(rv == net::OK);
  (*backend)->DoomAllEntries(base::Bind(&Noop, completion));
}

void ClearHttpDiskCacheOfContext(URLRequestContextGetter* context_getter,
                                 base::WaitableEvent* completion) {
  typedef Backend* BackendPtr;  // Make line below easier to understand.
  BackendPtr* backend_ptr = new BackendPtr(NULL);
  CompletionCallback callback(base::Bind(&CallDoomAllEntries,
                                         base::Owned(backend_ptr),
                                         completion));

  int rv = context_getter->GetURLRequestContext()->
    http_transaction_factory()->GetCache()->GetBackend(backend_ptr, callback);

  // If not net::ERR_IO_PENDING, then backend pointer is updated but callback
  // is not called, so call it explicitly.
  if (rv != net::ERR_IO_PENDING)
    callback.Run(net::OK);
}

void ClearHttpDiskCacheOnIoThread(
    URLRequestContextGetter* main_context_getter,
    URLRequestContextGetter* media_context_getter,
    base::WaitableEvent* completion1,
    base::WaitableEvent* completion2) {
  ClearHttpDiskCacheOfContext(main_context_getter, completion1);
  ClearHttpDiskCacheOfContext(media_context_getter, completion2);
}

}  // namespace

namespace nw {

void RemoveHttpDiskCache(content::BrowserContext* browser_context,
                        int renderer_child_id) {
  URLRequestContextGetter* main_context_getter =
      browser_context->GetRequestContextForRenderProcess(renderer_child_id);
  URLRequestContextGetter* media_context_getter =
      browser_context->GetMediaRequestContextForRenderProcess(
          renderer_child_id);

  base::WaitableEvent comp1(false, false), comp2(false, false);
  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(&ClearHttpDiskCacheOnIoThread,
                 base::Unretained(main_context_getter),
                 base::Unretained(media_context_getter),
                 &comp1, &comp2));
  comp1.Wait();
  comp2.Wait();
}

}  // namespace nw
<commit_msg>Fix crash in ClearCache in some cases<commit_after>// Copyright (c) 2012 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 "net_disk_cache_remover.h"

#include "base/bind_helpers.h"
#include "base/synchronization/waitable_event.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "net/disk_cache/disk_cache.h"
#include "net/http/http_cache.h"
#include "net/http/http_transaction_factory.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_context.h"
#include "net/base/completion_callback.h"

using content::BrowserThread;
using disk_cache::Backend;
using net::CompletionCallback;
using net::URLRequestContextGetter;

namespace {
// Everything is called and accessed on the IO thread.

void Noop(base::WaitableEvent* completion, int rv) {
  DCHECK(rv == net::OK);
  if (completion)
    completion->Signal();
}

void CallDoomAllEntries(Backend** backend, base::WaitableEvent* completion, int rv) {
  DCHECK(rv == net::OK);
  if (backend && *backend)
    (*backend)->DoomAllEntries(base::Bind(&Noop, completion));
}

void ClearHttpDiskCacheOfContext(URLRequestContextGetter* context_getter,
                                 base::WaitableEvent* completion) {
  typedef Backend* BackendPtr;  // Make line below easier to understand.
  BackendPtr* backend_ptr = new BackendPtr(NULL);
  CompletionCallback callback(base::Bind(&CallDoomAllEntries,
                                         base::Owned(backend_ptr),
                                         completion));

  int rv = context_getter->GetURLRequestContext()->
    http_transaction_factory()->GetCache()->GetBackend(backend_ptr, callback);

  // If not net::ERR_IO_PENDING, then backend pointer is updated but callback
  // is not called, so call it explicitly.
  if (rv != net::ERR_IO_PENDING)
    callback.Run(net::OK);
}

void ClearHttpDiskCacheOnIoThread(
    URLRequestContextGetter* main_context_getter,
    URLRequestContextGetter* media_context_getter,
    base::WaitableEvent* completion1,
    base::WaitableEvent* completion2) {
  ClearHttpDiskCacheOfContext(main_context_getter, completion1);
  ClearHttpDiskCacheOfContext(media_context_getter, completion2);
}

}  // namespace

namespace nw {

void RemoveHttpDiskCache(content::BrowserContext* browser_context,
                        int renderer_child_id) {
  URLRequestContextGetter* main_context_getter =
      browser_context->GetRequestContextForRenderProcess(renderer_child_id);
  URLRequestContextGetter* media_context_getter =
      browser_context->GetMediaRequestContextForRenderProcess(
          renderer_child_id);

  base::WaitableEvent comp1(false, false), comp2(false, false);
  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(&ClearHttpDiskCacheOnIoThread,
                 base::Unretained(main_context_getter),
                 base::Unretained(media_context_getter),
                 &comp1, &comp2));
  comp1.Wait();
  comp2.Wait();
}

}  // namespace nw
<|endoftext|>


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

#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/console/parse.h>
#include <pcl/common/time.h>

#include <pcl/compression/organized_pointcloud_compression.h>

#include <iostream>
#include <vector>
#include <stdio.h>
#include <sstream>
#include <stdlib.h>
#include <iostream>
#include <string>

#include <boost/asio.hpp>

using boost::asio::ip::tcp;

using namespace pcl;
using namespace pcl::io;

using namespace std;

char usage[] = "\n"
  "  PCL organized point cloud stream compression\n"
  "\n"
  "  usage: ./pcl_openni_organized_compression [mode] [parameters]\n"
  "\n"
  "  I/O: \n"
  "      -f file  : file name \n"
  "\n"
  "  file compression mode:\n"
  "      -x: encode point cloud stream to file\n"
  "      -d: decode from file and display point cloud stream\n"
  "\n"
  "  network streaming mode:\n"
  "      -s       : start server on localhost\n"
  "      -c host  : connect to server and display decoded cloud stream\n"
  "\n"
  "  optional compression parameters:\n"
  "      -a       : enable color coding\n"
  "      -t       : output statistics\n"
  "      -e       : show input cloud during encoding\n"

  "\n"
  "  example:\n"
  "      ./pcl_openni_organized_compression -x -t -f pc_compressed.pcc \n"
  "\n";

#define FPS_CALC(_WHAT_) \
do \
{ \
    static unsigned count = 0;\
    static double last = pcl::getTime ();\
    double now = pcl::getTime (); \
    ++count; \
    if (now - last >= 1.0) \
    { \
      std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" <<  std::endl; \
      count = 0; \
      last = now; \
    } \
}while(false)

void
print_usage (std::string msg)
{
  std::cerr << msg << std::endl;
  std::cout << usage << std::endl;
}

class SimpleOpenNIViewer
{
  public:
    SimpleOpenNIViewer (ostream& outputFile_arg,
                        OrganizedPointCloudCompression<PointXYZRGBA>* octreeEncoder_arg,
                        bool doColorEncoding_arg,
                        bool bShowStatistics_arg,
                        int pngLevel_arg = -1) :
    viewer ("Input Point Cloud - PCL Compression Viewer"),
    outputFile_ (outputFile_arg),
    organizedEncoder_ (octreeEncoder_arg),
    doColorEncoding_ (doColorEncoding_arg),
    bShowStatistics_ (bShowStatistics_arg),
    pngLevel_ (pngLevel_arg)
    {
    }

    void cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr &cloud)
    {
      if (!viewer.wasStopped ())
      {
        organizedEncoder_->encodePointCloud (cloud, outputFile_, doColorEncoding_, bShowStatistics_, pngLevel_);

        viewer.showCloud (cloud);
      }
    }

    void run ()
    {

      // create a new grabber for OpenNI devices
      pcl::Grabber* interface = new pcl::OpenNIGrabber();

      // make callback function from member function
      boost::function<void (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr&)> f =
        boost::bind (&SimpleOpenNIViewer::cloud_cb_, this, _1);

      // connect callback function for desired signal. In this case its a point cloud with color values
      boost::signals2::connection c = interface->registerCallback (f);

      // start receiving point clouds
      interface->start ();

      while (!outputFile_.fail())
      {
        boost::this_thread::sleep(boost::posix_time::seconds(1));
      }

      interface->stop ();
    }

    pcl::visualization::CloudViewer viewer;
    ostream& outputFile_;
    OrganizedPointCloudCompression<PointXYZRGBA>* organizedEncoder_;
    bool doColorEncoding_;
    bool bShowStatistics_;
    int pngLevel_;
};

struct EventHelper
{
  EventHelper (ostream& outputFile_arg,
               OrganizedPointCloudCompression<PointXYZRGBA>* octreeEncoder_arg,
               bool doColorEncoding_arg,
               bool bShowStatistics_arg,
               int pngLevel_arg = -1) :
  outputFile_ (outputFile_arg),
  organizedEncoder_ (octreeEncoder_arg),
  doColorEncoding_ (doColorEncoding_arg),
  bShowStatistics_ (bShowStatistics_arg),
  pngLevel_ (pngLevel_arg)
  {
  }

  void
  cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr &cloud)
  {
    if (!outputFile_.fail ())
    {
      organizedEncoder_->encodePointCloud (cloud, outputFile_, doColorEncoding_, bShowStatistics_, pngLevel_);
    }
  }

  void
  run ()
  {
    // create a new grabber for OpenNI devices
    pcl::Grabber* interface = new pcl::OpenNIGrabber ();

    // make callback function from member function
    boost::function<void
    (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr&)> f = boost::bind (&EventHelper::cloud_cb_, this, _1);

    // connect callback function for desired signal. In this case its a point cloud with color values
    boost::signals2::connection c = interface->registerCallback (f);

    // start receiving point clouds
    interface->start ();

    while (!outputFile_.fail ())
    {
      boost::this_thread::sleep(boost::posix_time::seconds(1));
    }

    interface->stop ();
  }

  ostream& outputFile_;
  OrganizedPointCloudCompression<PointXYZRGBA>* organizedEncoder_;
  bool doColorEncoding_;
  bool bShowStatistics_;
  int pngLevel_;
};

int
main (int argc, char **argv)
{
  OrganizedPointCloudCompression<PointXYZRGBA>* organizedCoder;

  bool showStatistics;
  bool doColorEncoding;
  bool bShowInputCloud;

  std::string fileName = "pc_compressed.pcc";
  std::string hostName = "localhost";

  bool bServerFileMode;
  bool bEnDecode;
  bool validArguments;

  validArguments = false;
  bServerFileMode = false;
  bEnDecode = false;

  showStatistics = false;
  doColorEncoding = false;
  bShowInputCloud = false;

  if (pcl::console::find_argument (argc, argv, "-e")>0)
    bShowInputCloud = true;

  if (pcl::console::find_argument (argc, argv, "-s")>0)
  {
    bEnDecode = true;
    bServerFileMode = true;
    validArguments = true;
  }

  if (pcl::console::parse_argument (argc, argv, "-c", hostName)>0)
  {
    bEnDecode = false;
    bServerFileMode = true;
    validArguments = true;
  }

  if (pcl::console::find_argument (argc, argv, "-a")>0)
  {
    doColorEncoding = true;
  }

  if (pcl::console::find_argument (argc, argv, "-x")>0)
  {
    bEnDecode = true;
    bServerFileMode = false;
    validArguments = true;
  }

  if (pcl::console::find_argument (argc, argv, "-d")>0)
  {
    bEnDecode = false;
    bServerFileMode = false;
    validArguments = true;
  }

  if (pcl::console::find_argument (argc, argv, "-t")>0)
    showStatistics = true;

  pcl::console::parse_argument (argc, argv, "-f", fileName);

  if (pcl::console::find_argument (argc, argv, "-?")>0)
  {
    print_usage ("");
    return 1;
  }

  if (!validArguments)
  {
    print_usage ("Please specify compression mode..\n");
    return -1;
  }

  organizedCoder = new OrganizedPointCloudCompression<PointXYZRGBA> ();

  if (!bServerFileMode)
  {
    if (bEnDecode)
    {
      // ENCODING
      ofstream compressedPCFile;
      compressedPCFile.open (fileName.c_str(), ios::out | ios::trunc | ios::binary);

      if (!bShowInputCloud)
      {
        EventHelper v (compressedPCFile, organizedCoder, doColorEncoding, showStatistics);
        v.run ();
      }
      else
      {
        SimpleOpenNIViewer v (compressedPCFile, organizedCoder, doColorEncoding, showStatistics);
        v.run ();
      }

    } else
    {
      // DECODING
      ifstream compressedPCFile;
      compressedPCFile.open (fileName.c_str(), ios::in | ios::binary);
      compressedPCFile.seekg (0);
      compressedPCFile.unsetf (ios_base::skipws);

      pcl::visualization::CloudViewer viewer ("PCL Compression Viewer");

      while (!compressedPCFile.eof())
      {
        PointCloud<PointXYZRGBA>::Ptr cloudOut (new PointCloud<PointXYZRGBA> ());
        organizedCoder->decodePointCloud ( compressedPCFile, cloudOut );
        viewer.showCloud (cloudOut);
      }
    }
  } else
  {
    if (bEnDecode)
    {
      // ENCODING
      try
      {
        boost::asio::io_service io_service;
        tcp::endpoint endpoint (tcp::v4 (), 6666);
        tcp::acceptor acceptor (io_service, endpoint);

        tcp::iostream socketStream;

        std::cout << "Waiting for connection.." << std::endl;

        acceptor.accept (*socketStream.rdbuf ());

        std::cout << "Connected!" << std::endl;

        if (!bShowInputCloud)
        {
          EventHelper v (socketStream, organizedCoder, doColorEncoding, showStatistics);
          v.run ();
        }
        else
        {
          SimpleOpenNIViewer v (socketStream, organizedCoder, doColorEncoding, showStatistics);
          v.run ();
        }

        std::cout << "Disconnected!" << std::endl;

        boost::this_thread::sleep(boost::posix_time::seconds(3));

      }
      catch (std::exception& e)
      {
        std::cerr << e.what () << std::endl;
      }
    }
    else
    {
      // DECODING
      std::cout << "Connecting to: " << hostName << ".." << std::endl;

      try
      {
        tcp::iostream socketStream (hostName.c_str (), "6666");

        std::cout << "Connected!" << std::endl;

        pcl::visualization::CloudViewer viewer ("Decoded Point Cloud - PCL Compression Viewer");

        while (!socketStream.fail())
        {
          FPS_CALC ("drawing");
          PointCloud<PointXYZRGBA>::Ptr cloudOut (new PointCloud<PointXYZRGBA> ());
          organizedCoder->decodePointCloud (socketStream, cloudOut);
          viewer.showCloud (cloudOut);
        }

      }
      catch (std::exception& e)
      {
        std::cout << "Exception: " << e.what () << std::endl;
      }
    }
  }

  delete (organizedCoder);
  return (0);
}

<commit_msg>added option to openni_organized_compression to enable disparity raw coding <commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * Author: Julius Kammerl (julius@kammerl.de)
 */

#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/console/parse.h>
#include <pcl/common/time.h>

#include <pcl/compression/organized_pointcloud_compression.h>

#include <iostream>
#include <vector>
#include <stdio.h>
#include <sstream>
#include <stdlib.h>
#include <iostream>
#include <string>

#include <boost/asio.hpp>

using boost::asio::ip::tcp;

using namespace pcl;
using namespace pcl::io;

using namespace std;

char usage[] = "\n"
  "  PCL organized point cloud stream compression\n"
  "\n"
  "  usage: ./pcl_openni_organized_compression [mode] [parameters]\n"
  "\n"
  "  I/O: \n"
  "      -f file  : file name \n"
  "\n"
  "  file compression mode:\n"
  "      -x: encode point cloud stream to file\n"
  "      -d: decode from file and display point cloud stream\n"
  "\n"
  "  network streaming mode:\n"
  "      -s       : start server on localhost\n"
  "      -c host  : connect to server and display decoded cloud stream\n"
  "\n"
  "  optional compression parameters:\n"
  "      -a       : enable color coding\n"
  "      -t       : output statistics\n"
  "      -e       : show input cloud during encoding\n"
  "      -r       : raw encoding of disparity maps\n"

  "\n"
  "  example:\n"
  "      ./pcl_openni_organized_compression -x -t -f pc_compressed.pcc \n"
  "\n";

#define FPS_CALC(_WHAT_) \
do \
{ \
    static unsigned count = 0;\
    static double last = pcl::getTime ();\
    double now = pcl::getTime (); \
    ++count; \
    if (now - last >= 1.0) \
    { \
      std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" <<  std::endl; \
      count = 0; \
      last = now; \
    } \
}while(false)

void
print_usage (std::string msg)
{
  std::cerr << msg << std::endl;
  std::cout << usage << std::endl;
}

class SimpleOpenNIViewer
{
  public:
    SimpleOpenNIViewer (ostream& outputFile_arg,
                        OrganizedPointCloudCompression<PointXYZRGBA>* octreeEncoder_arg,
                        bool doColorEncoding_arg,
                        bool bShowStatistics_arg,
                        bool bRawImageEncoding_arg,
                        int pngLevel_arg = -1) :
    viewer ("Input Point Cloud - PCL Compression Viewer"),
    outputFile_ (outputFile_arg),
    organizedEncoder_ (octreeEncoder_arg),
    doColorEncoding_ (doColorEncoding_arg),
    bShowStatistics_ (bShowStatistics_arg),
    bRawImageEncoding_ (bRawImageEncoding_arg),
    pngLevel_ (pngLevel_arg)
    {
    }

    void cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr &cloud)
    {
      if (!viewer.wasStopped ())
      {
        organizedEncoder_->encodePointCloud (cloud, outputFile_, doColorEncoding_, bShowStatistics_, pngLevel_);

        viewer.showCloud (cloud);
      }
    }

    void run ()
    {

      if (!bRawImageEncoding_)
      {
        // create a new grabber for OpenNI devices
        pcl::Grabber* interface = new pcl::OpenNIGrabber();

        // make callback function from member function
        boost::function<void (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr&)> f =
          boost::bind (&SimpleOpenNIViewer::cloud_cb_, this, _1);

        // connect callback function for desired signal. In this case its a point cloud with color values
        boost::signals2::connection c = interface->registerCallback (f);

        // start receiving point clouds
        interface->start ();

        while (!outputFile_.fail())
        {
          boost::this_thread::sleep(boost::posix_time::seconds(1));
        }

        interface->stop ();
      }

    }

    pcl::visualization::CloudViewer viewer;
    ostream& outputFile_;
    OrganizedPointCloudCompression<PointXYZRGBA>* organizedEncoder_;
    bool doColorEncoding_;
    bool bShowStatistics_;
    bool bRawImageEncoding_;
    int pngLevel_;
};

struct EventHelper
{
  EventHelper (ostream& outputFile_arg,
               OrganizedPointCloudCompression<PointXYZRGBA>* octreeEncoder_arg,
               bool doColorEncoding_arg,
               bool bShowStatistics_arg,
               bool bRawImageEncoding_arg,
               int pngLevel_arg = -1) :
  outputFile_ (outputFile_arg),
  organizedEncoder_ (octreeEncoder_arg),
  doColorEncoding_ (doColorEncoding_arg),
  bShowStatistics_ (bShowStatistics_arg),
  bRawImageEncoding_ (bRawImageEncoding_arg),
  pngLevel_ (pngLevel_arg)
  {
  }

  void
  cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr &cloud)
  {
    if (!outputFile_.fail ())
    {
      organizedEncoder_->encodePointCloud (cloud, outputFile_, doColorEncoding_, bShowStatistics_, pngLevel_);
    }
  }

  void
  image_callback (const boost::shared_ptr<openni_wrapper::Image> &image,
                  const boost::shared_ptr<openni_wrapper::DepthImage> &depth_image, float)
  {

    vector<uint16_t> disparity_data;
    vector<uint8_t> rgb_data;

    uint32_t width=depth_image->getWidth ();
    uint32_t height=depth_image->getHeight ();

    disparity_data.resize(width*height);
    depth_image->fillDepthImageRaw(width, height, &disparity_data[0], width*sizeof(uint16_t));

    if (image->getEncoding() != openni_wrapper::Image::RGB)
    {
      rgb_data.resize(width*height*3);
      image->fillRGB(width, height, &rgb_data[0], width*sizeof(uint8_t)*3);
    }

    organizedEncoder_->encodeRawDisparityMapWithColorImage (disparity_data, rgb_data, width, height, outputFile_, doColorEncoding_, bShowStatistics_, pngLevel_);

  }

  void
  run ()
  {
    if (!bRawImageEncoding_)
    {
      // create a new grabber for OpenNI devices
      pcl::Grabber* interface = new pcl::OpenNIGrabber ();

      // make callback function from member function
      boost::function<void
      (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr&)> f = boost::bind (&EventHelper::cloud_cb_, this, _1);

      // connect callback function for desired signal. In this case its a point cloud with color values
      boost::signals2::connection c = interface->registerCallback (f);

      // start receiving point clouds
      interface->start ();

      while (!outputFile_.fail ())
      {
        boost::this_thread::sleep(boost::posix_time::seconds(1));
      }

      interface->stop ();
    } else
    {
      pcl::OpenNIGrabber::Mode image_mode = pcl::OpenNIGrabber::OpenNI_Default_Mode;
      int depthformat = openni_wrapper::OpenNIDevice::OpenNI_shift_values;

      pcl::OpenNIGrabber grabber ("", pcl::OpenNIGrabber::OpenNI_Default_Mode, image_mode);

      // Set the depth output format
      grabber.getDevice ()->setDepthOutputFormat (static_cast<openni_wrapper::OpenNIDevice::DepthMode> (depthformat));

      boost::function<void (const boost::shared_ptr<openni_wrapper::Image>&, const boost::shared_ptr<openni_wrapper::DepthImage>&, float) > image_cb = boost::bind (&EventHelper::image_callback, this, _1, _2, _3);
      boost::signals2::connection image_connection = grabber.registerCallback (image_cb);

      grabber.start ();
      while (!outputFile_.fail())
      {
        boost::this_thread::sleep(boost::posix_time::seconds(1));
      }
      grabber.stop ();

    }
  }

  ostream& outputFile_;
  OrganizedPointCloudCompression<PointXYZRGBA>* organizedEncoder_;
  bool doColorEncoding_;
  bool bShowStatistics_;
  bool bRawImageEncoding_;
  int pngLevel_;
};

int
main (int argc, char **argv)
{
  OrganizedPointCloudCompression<PointXYZRGBA>* organizedCoder;

  bool showStatistics;
  bool doColorEncoding;
  bool bShowInputCloud;
  bool bRawImageEncoding;

  std::string fileName = "pc_compressed.pcc";
  std::string hostName = "localhost";

  bool bServerFileMode;
  bool bEnDecode;
  bool validArguments;

  validArguments = false;
  bServerFileMode = false;
  bEnDecode = false;

  showStatistics = false;
  doColorEncoding = false;
  bShowInputCloud = false;
  bRawImageEncoding = false;

  if (pcl::console::find_argument (argc, argv, "-e")>0)
    bShowInputCloud = true;

  if (pcl::console::find_argument (argc, argv, "-r")>0)
    bRawImageEncoding = true;

  if (pcl::console::find_argument (argc, argv, "-s")>0)
  {
    bEnDecode = true;
    bServerFileMode = true;
    validArguments = true;
  }

  if (pcl::console::parse_argument (argc, argv, "-c", hostName)>0)
  {
    bEnDecode = false;
    bServerFileMode = true;
    validArguments = true;
  }

  if (pcl::console::find_argument (argc, argv, "-a")>0)
  {
    doColorEncoding = true;
  }

  if (pcl::console::find_argument (argc, argv, "-x")>0)
  {
    bEnDecode = true;
    bServerFileMode = false;
    validArguments = true;
  }

  if (pcl::console::find_argument (argc, argv, "-d")>0)
  {
    bEnDecode = false;
    bServerFileMode = false;
    validArguments = true;
  }

  if (pcl::console::find_argument (argc, argv, "-t")>0)
    showStatistics = true;

  pcl::console::parse_argument (argc, argv, "-f", fileName);

  if (pcl::console::find_argument (argc, argv, "-?")>0)
  {
    print_usage ("");
    return 1;
  }

  if (!validArguments)
  {
    print_usage ("Please specify compression mode..\n");
    return -1;
  }

  organizedCoder = new OrganizedPointCloudCompression<PointXYZRGBA> ();

  if (!bServerFileMode)
  {
    if (bEnDecode)
    {
      // ENCODING
      ofstream compressedPCFile;
      compressedPCFile.open (fileName.c_str(), ios::out | ios::trunc | ios::binary);

      if (!bShowInputCloud)
      {
        EventHelper v (compressedPCFile, organizedCoder, doColorEncoding, showStatistics, bRawImageEncoding);
        v.run ();
      }
      else
      {
        SimpleOpenNIViewer v (compressedPCFile, organizedCoder, doColorEncoding, showStatistics, bRawImageEncoding);
        v.run ();
      }

    } else
    {
      // DECODING
      ifstream compressedPCFile;
      compressedPCFile.open (fileName.c_str(), ios::in | ios::binary);
      compressedPCFile.seekg (0);
      compressedPCFile.unsetf (ios_base::skipws);

      pcl::visualization::CloudViewer viewer ("PCL Compression Viewer");

      while (!compressedPCFile.eof())
      {
        PointCloud<PointXYZRGBA>::Ptr cloudOut (new PointCloud<PointXYZRGBA> ());
        organizedCoder->decodePointCloud ( compressedPCFile, cloudOut );
        viewer.showCloud (cloudOut);
      }
    }
  } else
  {
    if (bEnDecode)
    {
      // ENCODING
      try
      {
        boost::asio::io_service io_service;
        tcp::endpoint endpoint (tcp::v4 (), 6666);
        tcp::acceptor acceptor (io_service, endpoint);

        tcp::iostream socketStream;

        std::cout << "Waiting for connection.." << std::endl;

        acceptor.accept (*socketStream.rdbuf ());

        std::cout << "Connected!" << std::endl;

        if (!bShowInputCloud)
        {
          EventHelper v (socketStream, organizedCoder, doColorEncoding, showStatistics, bRawImageEncoding);
          v.run ();
        }
        else
        {
          SimpleOpenNIViewer v (socketStream, organizedCoder, doColorEncoding, showStatistics, bRawImageEncoding);
          v.run ();
        }

        std::cout << "Disconnected!" << std::endl;

        boost::this_thread::sleep(boost::posix_time::seconds(3));

      }
      catch (std::exception& e)
      {
        std::cerr << e.what () << std::endl;
      }
    }
    else
    {
      // DECODING
      std::cout << "Connecting to: " << hostName << ".." << std::endl;

      try
      {
        tcp::iostream socketStream (hostName.c_str (), "6666");

        std::cout << "Connected!" << std::endl;

        pcl::visualization::CloudViewer viewer ("Decoded Point Cloud - PCL Compression Viewer");

        while (!socketStream.fail())
        {
          FPS_CALC ("drawing");
          PointCloud<PointXYZRGBA>::Ptr cloudOut (new PointCloud<PointXYZRGBA> ());
          organizedCoder->decodePointCloud (socketStream, cloudOut);
          viewer.showCloud (cloudOut);
        }

      }
      catch (std::exception& e)
      {
        std::cout << "Exception: " << e.what () << std::endl;
      }
    }
  }

  delete (organizedCoder);
  return (0);
}

<|endoftext|>


<commit_before>
#include <base/contract.h>
#include <base/unit_test.h>
#include <layout/solver.h>
#include <iostream>
#include <bitset>

namespace
{

int safemain( int argc, char *argv[] )
{
	base::unit_test test( "solver" );

	base::cmd_line options( argv[0] );
	test.setup( options );

	options.add_help();
	options.parse( argc, argv );

	if ( options["help"] )
	{
		std::cerr << options << std::endl;
		return -1;
	}

	test["simple"] = [&]( void )
	{
		layout::solver s;
		layout::variable x0( "x0" );
		layout::variable x1( "x1" );

		s.add_variable( x1, 1.0 );
		s.add_constraint( x0 >= 0 );
		s.add_constraint( x1 >= 0 );
		s.add_constraint( ( x0 * 2 ) == x1 );
		s.suggest_value( x1, 1 );

		s.update_variables();

		std::cout << x0 << " = " << x0.value() << '\n';
		std::cout << x1 << " = " << x1.value() << '\n';
	};

	test.run( options );

	return 0;
}

}

int main( int argc, char *argv[] )
{
	try
	{
		return safemain( argc, argv );
	}
	catch ( const std::exception &e )
	{
		std::cerr << '\n';
		base::print_exception( std::cerr, e );
	}
}
<commit_msg>Fixed renamed function in test.<commit_after>
#include <base/contract.h>
#include <base/unit_test.h>
#include <layout/solver.h>
#include <iostream>
#include <bitset>

namespace
{

int safemain( int argc, char *argv[] )
{
	base::unit_test test( "solver" );

	base::cmd_line options( argv[0] );
	test.setup( options );

	options.add_help();
	options.parse( argc, argv );

	if ( options["help"] )
	{
		std::cerr << options << std::endl;
		return -1;
	}

	test["simple"] = [&]( void )
	{
		layout::solver s;
		layout::variable x0( "x0" );
		layout::variable x1( "x1" );

		s.add_variable( x1, 1.0 );
		s.add_constraint( x0 >= 0 );
		s.add_constraint( x1 >= 0 );
		s.add_constraint( ( x0 * 2 ) == x1 );
		s.suggest( x1, 1 );

		s.update_variables();

		std::cout << x0 << " = " << x0.value() << '\n';
		std::cout << x1 << " = " << x1.value() << '\n';
	};

	test.run( options );

	return 0;
}

}

int main( int argc, char *argv[] )
{
	try
	{
		return safemain( argc, argv );
	}
	catch ( const std::exception &e )
	{
		std::cerr << '\n';
		base::print_exception( std::cerr, e );
	}
}
<|endoftext|>


<commit_before>/*
    Copyright (C) 2001 by Jorrit Tyberghein

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "cssys/sysfunc.h"
#include "iutil/vfs.h"
#include "csutil/cscolor.h"
#include "cstool/csview.h"
#include "cstool/initapp.h"
#include "simplecloth.h"
#include "iutil/eventq.h"
#include "iutil/event.h"
#include "iutil/objreg.h"
#include "iutil/csinput.h"
#include "iutil/virtclk.h"
#include "iengine/sector.h"
#include "iengine/engine.h"
#include "iengine/camera.h"
#include "iengine/light.h"
#include "iengine/statlght.h"
#include "iengine/texture.h"
#include "iengine/mesh.h"
#include "iengine/movable.h"
#include "iengine/material.h"
#include "imesh/thing/polygon.h"
#include "imesh/thing/thing.h"
#include "imesh/genmesh.h"
#include "imesh/object.h"
#include "ivideo/graph3d.h"
#include "ivideo/graph2d.h"
#include "ivideo/txtmgr.h"
#include "ivideo/texture.h"
#include "ivideo/material.h"
#include "ivideo/fontserv.h"
#include "igraphic/imageio.h"
#include "imap/parser.h"
#include "ivaria/reporter.h"
#include "ivaria/stdrep.h"
#include "csutil/cmdhelp.h"

CS_IMPLEMENT_APPLICATION

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

// The global pointer to simple
Simple *simple;

Simple::Simple (iObjectRegistry* object_reg)
{
  Simple::object_reg = object_reg;
}

Simple::~Simple ()
{
}

void Simple::SetupFrame ()
{
  // First get elapsed time from the virtual clock.
  csTicks elapsed_time = vc->GetElapsedTicks ();

  // Now rotate the camera according to keyboard state
  float speed = (elapsed_time / 1000.0) * (0.03 * 20);

  iCamera* c = view->GetCamera();
  if (kbd->GetKeyState (CSKEY_RIGHT))
    c->GetTransform ().RotateThis (CS_VEC_ROT_RIGHT, speed);
  if (kbd->GetKeyState (CSKEY_LEFT))
    c->GetTransform ().RotateThis (CS_VEC_ROT_LEFT, speed);
  if (kbd->GetKeyState (CSKEY_PGUP))
    c->GetTransform ().RotateThis (CS_VEC_TILT_UP, speed);
  if (kbd->GetKeyState (CSKEY_PGDN))
    c->GetTransform ().RotateThis (CS_VEC_TILT_DOWN, speed);
  if (kbd->GetKeyState (CSKEY_UP))
    c->Move (CS_VEC_FORWARD * 4 * speed);
  if (kbd->GetKeyState (CSKEY_DOWN))
    c->Move (CS_VEC_BACKWARD * 4 * speed);

  // Tell 3D driver we're going to display 3D things.
  if (!g3d->BeginDraw (engine->GetBeginDrawFlags () | CSDRAW_3DGRAPHICS))
    return;

  // Tell the camera to render into the frame buffer.
  view->Draw ();
}

void Simple::FinishFrame ()
{
  g3d->FinishDraw ();
  g3d->Print (NULL);
}

bool Simple::HandleEvent (iEvent& ev)
{
  if (ev.Type == csevBroadcast && ev.Command.Code == cscmdProcess)
  {
    simple->SetupFrame ();
    return true;
  }
  else if (ev.Type == csevBroadcast && ev.Command.Code == cscmdFinalProcess)
  {
    simple->FinishFrame ();
    return true;
  }
  else if (ev.Type == csevKeyDown && ev.Key.Code == CSKEY_ESC)
  {
    csRef<iEventQueue> q (CS_QUERY_REGISTRY (object_reg, iEventQueue));
    if (q) q->GetEventOutlet()->Broadcast (cscmdQuit);
    return true;
  }

  return false;
}

bool Simple::SimpleEventHandler (iEvent& ev)
{
  return simple->HandleEvent (ev);
}

bool Simple::Initialize ()
{
  if (!csInitializer::RequestPlugins (object_reg,
  	CS_REQUEST_VFS,
	CS_REQUEST_SOFTWARE3D,
	CS_REQUEST_ENGINE,
	CS_REQUEST_FONTSERVER,
	CS_REQUEST_IMAGELOADER,
	CS_REQUEST_LEVELLOADER,
	CS_REQUEST_REPORTER,
	CS_REQUEST_REPORTERLISTENER,
	CS_REQUEST_END))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
	"Can't initialize plugins!");
    return false;
  }

  if (!csInitializer::SetupEventHandler (object_reg, SimpleEventHandler))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
	"Can't initialize event handler!");
    return false;
  }

  // Check for commandline help.
  if (csCommandLineHelper::CheckHelp (object_reg))
  {
    csCommandLineHelper::Help (object_reg);
    return false;
  }

  // The virtual clock.
  vc = CS_QUERY_REGISTRY (object_reg, iVirtualClock);
  if (vc == NULL)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
	"Can't find the virtual clock!");
    return false;
  }

  // Find the pointer to engine plugin
  engine = CS_QUERY_REGISTRY (object_reg, iEngine);
  if (engine == NULL)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
	"No iEngine plugin!");
    return false;
  }

  loader = CS_QUERY_REGISTRY (object_reg, iLoader);
  if (loader == NULL)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
    	"No iLoader plugin!");
    return false;
  }

  g3d = CS_QUERY_REGISTRY (object_reg, iGraphics3D);
  if (g3d == NULL)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
    	"No iGraphics3D plugin!");
    return false;
  }

  kbd = CS_QUERY_REGISTRY (object_reg, iKeyboardDriver);
  if (kbd == NULL)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
    	"No iKeyboardDriver plugin!");
    return false;
  }

  // Open the main system. This will open all the previously loaded plug-ins.
  if (!csInitializer::OpenApplication (object_reg))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
    	"Error opening system!");
    return false;
  }

  // First disable the lighting cache. Our app is simple enough
  // not to need this.
  engine->SetLightingCacheMode (0);

  if (!loader->LoadTexture ("stone", "/lib/std/stone4.gif"))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
    	"Error loading 'stone4' texture!");
    return false;
  }
  iMaterialWrapper* tm = engine->GetMaterialList ()->FindByName ("stone");

  room = engine->CreateSector ("room");
  csRef<iMeshWrapper> walls (engine->CreateSectorWallsMesh (room, "walls"));
  csRef<iThingState> walls_state (
  	SCF_QUERY_INTERFACE (walls->GetMeshObject (), iThingState));
  iPolygon3D* p;
  p = walls_state->CreatePolygon ();
  p->SetMaterial (tm);
  p->CreateVertex (csVector3 (-10, 0, 10));
  p->CreateVertex (csVector3 (10, 0, 10));
  p->CreateVertex (csVector3 (10, 0, -10));
  p->CreateVertex (csVector3 (-10, 0, -10));
  p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);

  p = walls_state->CreatePolygon ();
  p->SetMaterial (tm);
  p->CreateVertex (csVector3 (-10, 20, -10));
  p->CreateVertex (csVector3 (10, 20, -10));
  p->CreateVertex (csVector3 (10, 20, 10));
  p->CreateVertex (csVector3 (-10, 20, 10));
  p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);

  p = walls_state->CreatePolygon ();
  p->SetMaterial (tm);
  p->CreateVertex (csVector3 (-10, 20, 10));
  p->CreateVertex (csVector3 (10, 20, 10));
  p->CreateVertex (csVector3 (10, 0,10));
  p->CreateVertex (csVector3 (-10, 0, 10));
  p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);

  p = walls_state->CreatePolygon ();
  p->SetMaterial (tm);
  p->CreateVertex (csVector3 (10, 20, 10));
  p->CreateVertex (csVector3 (10, 20, -10));
  p->CreateVertex (csVector3 (10, 0, -10));
  p->CreateVertex (csVector3 (10, 0, 10));
  p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);

  p = walls_state->CreatePolygon ();
  p->SetMaterial (tm);
  p->CreateVertex (csVector3 (-10, 20, -10));
  p->CreateVertex (csVector3 (-10, 20, 10));
  p->CreateVertex (csVector3 (-10, 0, 10));
  p->CreateVertex (csVector3 (-10, 0, -10));
  p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);

  p = walls_state->CreatePolygon ();
  p->SetMaterial (tm);
  p->CreateVertex (csVector3 (10, 20, -10));
  p->CreateVertex (csVector3 (-10, 20, -10));
  p->CreateVertex (csVector3 (-10, 0, -10));
  p->CreateVertex (csVector3 (10, 0, -10));
  p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);

  csRef<iStatLight> light;
  iLightList* ll = room->GetLights ();

  light = engine->CreateLight (NULL, csVector3 (-3, 5, 0), 20,
  	csColor (1, 0, 0), false);
  ll->Add (light->QueryLight ());

  light = engine->CreateLight (NULL, csVector3 (3, 5,  0), 20,
  	csColor (0, 0, 1), false);
  ll->Add (light->QueryLight ());

  light = engine->CreateLight (NULL, csVector3 (0, 5, -3), 20,
  	csColor (0, 1, 0), false);
  ll->Add (light->QueryLight ());

  engine->Prepare ();

  view = csPtr<iView> (new csView (engine, g3d));
  view->GetCamera ()->SetSector (room);
  view->GetCamera ()->GetTransform ().SetOrigin (csVector3 (0, 5, -3));
  iGraphics2D* g2d = g3d->GetDriver2D ();
  view->SetRectangle (0, 0, g2d->GetWidth (), g2d->GetHeight ());

  iTextureManager* txtmgr = g3d->GetTextureManager ();
  txtmgr->SetPalette ();

  // Load a texture for our sprite.
  iTextureWrapper* txt = loader->LoadTexture ("spark",
  	"/lib/std/spark.png", CS_TEXTURE_3D, txtmgr, true);
  if (txt == NULL)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
    	"Error loading texture!");
    return false;
  }

  // Load a sprite template from disk.
  csRef<iMeshFactoryWrapper> imeshfact ( engine->CreateMeshFactory("crystalspace.mesh.object.cloth","StuffFactory") );
  csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
    	"BLA!!");
  csRef<iMaterialWrapper> mat ( engine->GetMaterialList()->FindByName("spark") );

  if (imeshfact == NULL)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
    	"Error loading mesh object factory!");
    return false;
  }

  if (mat == NULL)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
    	"Error loading material!!!");
    return false;
  }

  // Create the sprite and add it to the engine.
  csRef<iMeshWrapper> sprite (engine->CreateMeshWrapper (
  	imeshfact, "MySprite", room,
	csVector3 (-3, 5, 0)));
  csMatrix3 m; m.Identity (); // m *= 5.;
  sprite->GetMovable ()->SetTransform (m);
  sprite->GetMovable ()->UpdateMove ();
  csRef<iGeneralMeshState> spstate (SCF_QUERY_INTERFACE (sprite->GetMeshObject (), iGeneralMeshState));
  spstate->SetMaterialWrapper( mat );
  //spstate->SetAction ("default");

  // The following two calls are not needed since CS_ZBUF_USE and
  // Object render priority are the default but they show how you
  // can do this.
  //sprite->SetZBufMode (CS_ZBUF_USE);
  //sprite->SetRenderPriority (engine->GetObjectRenderPriority ());

  //sprite->DeferUpdateLighting (CS_NLIGHT_STATIC|CS_NLIGHT_DYNAMIC, 10);
  return true;
}

void Simple::Start ()
{
  csDefaultRunLoop (object_reg);
}

/*---------------------------------------------------------------------*
 * Main function
 *---------------------------------------------------------------------*/
int main (int argc, char* argv[])
{
  iObjectRegistry* object_reg = csInitializer::CreateEnvironment (argc, argv);

  simple = new Simple (object_reg);
  if (simple->Initialize ())
    simple->Start ();
  delete simple;

  csInitializer::DestroyApplication (object_reg);
  return 0;
}

<commit_msg>    now it positioned better<commit_after>/*
    Copyright (C) 2001 by Jorrit Tyberghein

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "cssys/sysfunc.h"
#include "iutil/vfs.h"
#include "csutil/cscolor.h"
#include "cstool/csview.h"
#include "cstool/initapp.h"
#include "simplecloth.h"
#include "iutil/eventq.h"
#include "iutil/event.h"
#include "iutil/objreg.h"
#include "iutil/csinput.h"
#include "iutil/virtclk.h"
#include "iengine/sector.h"
#include "iengine/engine.h"
#include "iengine/camera.h"
#include "iengine/light.h"
#include "iengine/statlght.h"
#include "iengine/texture.h"
#include "iengine/mesh.h"
#include "iengine/movable.h"
#include "iengine/material.h"
#include "imesh/thing/polygon.h"
#include "imesh/thing/thing.h"
#include "imesh/genmesh.h"
#include "imesh/object.h"
#include "ivideo/graph3d.h"
#include "ivideo/graph2d.h"
#include "ivideo/txtmgr.h"
#include "ivideo/texture.h"
#include "ivideo/material.h"
#include "ivideo/fontserv.h"
#include "igraphic/imageio.h"
#include "imap/parser.h"
#include "ivaria/reporter.h"
#include "ivaria/stdrep.h"
#include "csutil/cmdhelp.h"

CS_IMPLEMENT_APPLICATION

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

// The global pointer to simple
Simple *simple;

Simple::Simple (iObjectRegistry* object_reg)
{
  Simple::object_reg = object_reg;
}

Simple::~Simple ()
{
}

void Simple::SetupFrame ()
{
  // First get elapsed time from the virtual clock.
  csTicks elapsed_time = vc->GetElapsedTicks ();

  // Now rotate the camera according to keyboard state
  float speed = (elapsed_time / 1000.0) * (0.03 * 20);

  iCamera* c = view->GetCamera();
  if (kbd->GetKeyState (CSKEY_RIGHT))
    c->GetTransform ().RotateThis (CS_VEC_ROT_RIGHT, speed);
  if (kbd->GetKeyState (CSKEY_LEFT))
    c->GetTransform ().RotateThis (CS_VEC_ROT_LEFT, speed);
  if (kbd->GetKeyState (CSKEY_PGUP))
    c->GetTransform ().RotateThis (CS_VEC_TILT_UP, speed);
  if (kbd->GetKeyState (CSKEY_PGDN))
    c->GetTransform ().RotateThis (CS_VEC_TILT_DOWN, speed);
  if (kbd->GetKeyState (CSKEY_UP))
    c->Move (CS_VEC_FORWARD * 4 * speed);
  if (kbd->GetKeyState (CSKEY_DOWN))
    c->Move (CS_VEC_BACKWARD * 4 * speed);

  // Tell 3D driver we're going to display 3D things.
  if (!g3d->BeginDraw (engine->GetBeginDrawFlags () | CSDRAW_3DGRAPHICS))
    return;

  // Tell the camera to render into the frame buffer.
  view->Draw ();
}

void Simple::FinishFrame ()
{
  g3d->FinishDraw ();
  g3d->Print (NULL);
}

bool Simple::HandleEvent (iEvent& ev)
{
  if (ev.Type == csevBroadcast && ev.Command.Code == cscmdProcess)
  {
    simple->SetupFrame ();
    return true;
  }
  else if (ev.Type == csevBroadcast && ev.Command.Code == cscmdFinalProcess)
  {
    simple->FinishFrame ();
    return true;
  }
  else if (ev.Type == csevKeyDown && ev.Key.Code == CSKEY_ESC)
  {
    csRef<iEventQueue> q (CS_QUERY_REGISTRY (object_reg, iEventQueue));
    if (q) q->GetEventOutlet()->Broadcast (cscmdQuit);
    return true;
  }

  return false;
}

bool Simple::SimpleEventHandler (iEvent& ev)
{
  return simple->HandleEvent (ev);
}

bool Simple::Initialize ()
{
  if (!csInitializer::RequestPlugins (object_reg,
  	CS_REQUEST_VFS,
	CS_REQUEST_SOFTWARE3D,
	CS_REQUEST_ENGINE,
	CS_REQUEST_FONTSERVER,
	CS_REQUEST_IMAGELOADER,
	CS_REQUEST_LEVELLOADER,
	CS_REQUEST_REPORTER,
	CS_REQUEST_REPORTERLISTENER,
	CS_REQUEST_END))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
	"Can't initialize plugins!");
    return false;
  }

  if (!csInitializer::SetupEventHandler (object_reg, SimpleEventHandler))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
	"Can't initialize event handler!");
    return false;
  }

  // Check for commandline help.
  if (csCommandLineHelper::CheckHelp (object_reg))
  {
    csCommandLineHelper::Help (object_reg);
    return false;
  }

  // The virtual clock.
  vc = CS_QUERY_REGISTRY (object_reg, iVirtualClock);
  if (vc == NULL)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
	"Can't find the virtual clock!");
    return false;
  }

  // Find the pointer to engine plugin
  engine = CS_QUERY_REGISTRY (object_reg, iEngine);
  if (engine == NULL)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
	"No iEngine plugin!");
    return false;
  }

  loader = CS_QUERY_REGISTRY (object_reg, iLoader);
  if (loader == NULL)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
    	"No iLoader plugin!");
    return false;
  }

  g3d = CS_QUERY_REGISTRY (object_reg, iGraphics3D);
  if (g3d == NULL)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
    	"No iGraphics3D plugin!");
    return false;
  }

  kbd = CS_QUERY_REGISTRY (object_reg, iKeyboardDriver);
  if (kbd == NULL)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
    	"No iKeyboardDriver plugin!");
    return false;
  }

  // Open the main system. This will open all the previously loaded plug-ins.
  if (!csInitializer::OpenApplication (object_reg))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
    	"Error opening system!");
    return false;
  }

  // First disable the lighting cache. Our app is simple enough
  // not to need this.
  engine->SetLightingCacheMode (0);

  if (!loader->LoadTexture ("stone", "/lib/std/stone4.gif"))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
    	"Error loading 'stone4' texture!");
    return false;
  }
  iMaterialWrapper* tm = engine->GetMaterialList ()->FindByName ("stone");

  room = engine->CreateSector ("room");
  csRef<iMeshWrapper> walls (engine->CreateSectorWallsMesh (room, "walls"));
  csRef<iThingState> walls_state (
  	SCF_QUERY_INTERFACE (walls->GetMeshObject (), iThingState));
  iPolygon3D* p;
  p = walls_state->CreatePolygon ();
  p->SetMaterial (tm);
  p->CreateVertex (csVector3 (-10, 0, 10));
  p->CreateVertex (csVector3 (10, 0, 10));
  p->CreateVertex (csVector3 (10, 0, -10));
  p->CreateVertex (csVector3 (-10, 0, -10));
  p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);

  p = walls_state->CreatePolygon ();
  p->SetMaterial (tm);
  p->CreateVertex (csVector3 (-10, 20, -10));
  p->CreateVertex (csVector3 (10, 20, -10));
  p->CreateVertex (csVector3 (10, 20, 10));
  p->CreateVertex (csVector3 (-10, 20, 10));
  p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);

  p = walls_state->CreatePolygon ();
  p->SetMaterial (tm);
  p->CreateVertex (csVector3 (-10, 20, 10));
  p->CreateVertex (csVector3 (10, 20, 10));
  p->CreateVertex (csVector3 (10, 0,10));
  p->CreateVertex (csVector3 (-10, 0, 10));
  p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);

  p = walls_state->CreatePolygon ();
  p->SetMaterial (tm);
  p->CreateVertex (csVector3 (10, 20, 10));
  p->CreateVertex (csVector3 (10, 20, -10));
  p->CreateVertex (csVector3 (10, 0, -10));
  p->CreateVertex (csVector3 (10, 0, 10));
  p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);

  p = walls_state->CreatePolygon ();
  p->SetMaterial (tm);
  p->CreateVertex (csVector3 (-10, 20, -10));
  p->CreateVertex (csVector3 (-10, 20, 10));
  p->CreateVertex (csVector3 (-10, 0, 10));
  p->CreateVertex (csVector3 (-10, 0, -10));
  p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);

  p = walls_state->CreatePolygon ();
  p->SetMaterial (tm);
  p->CreateVertex (csVector3 (10, 20, -10));
  p->CreateVertex (csVector3 (-10, 20, -10));
  p->CreateVertex (csVector3 (-10, 0, -10));
  p->CreateVertex (csVector3 (10, 0, -10));
  p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);

  csRef<iStatLight> light;
  iLightList* ll = room->GetLights ();

  light = engine->CreateLight (NULL, csVector3 (-3, 5, 0), 20,
  	csColor (1, 0, 0), false);
  ll->Add (light->QueryLight ());

  light = engine->CreateLight (NULL, csVector3 (3, 5,  0), 20,
  	csColor (0, 0, 1), false);
  ll->Add (light->QueryLight ());

  light = engine->CreateLight (NULL, csVector3 (0, 5, -3), 20,
  	csColor (0, 1, 0), false);
  ll->Add (light->QueryLight ());

  engine->Prepare ();

  view = csPtr<iView> (new csView (engine, g3d));
  view->GetCamera ()->SetSector (room);
  view->GetCamera ()->GetTransform ().SetOrigin (csVector3 (0, 5, -3));
  iGraphics2D* g2d = g3d->GetDriver2D ();
  view->SetRectangle (0, 0, g2d->GetWidth (), g2d->GetHeight ());

  iTextureManager* txtmgr = g3d->GetTextureManager ();
  txtmgr->SetPalette ();

  // Load a texture for our sprite.
  iTextureWrapper* txt = loader->LoadTexture ("spark",
  	"/lib/std/spark.png", CS_TEXTURE_3D, txtmgr, true);
  if (txt == NULL)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
    	"Error loading texture!");
    return false;
  }

  // Load a sprite template from disk.
  csRef<iMeshFactoryWrapper> imeshfact ( engine->CreateMeshFactory("crystalspace.mesh.object.cloth","StuffFactory") );
  csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
    	"BLA!!");
  csRef<iMaterialWrapper> mat ( engine->GetMaterialList()->FindByName("spark") );

  if (imeshfact == NULL)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
    	"Error loading mesh object factory!");
    return false;
  }

  if (mat == NULL)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple2",
    	"Error loading material!!!");
    return false;
  }

  // Create the sprite and add it to the engine.
  csRef<iMeshWrapper> sprite (engine->CreateMeshWrapper (
  	imeshfact, "MySprite", room,
	csVector3 (-1, 4, 0)));
  csMatrix3 m; m.Identity (); // m *= 5.;
  sprite->GetMovable ()->SetTransform (m);
  sprite->GetMovable ()->UpdateMove ();
  csRef<iGeneralMeshState> spstate (SCF_QUERY_INTERFACE (sprite->GetMeshObject (), iGeneralMeshState));
  spstate->SetMaterialWrapper( mat );
  //spstate->SetAction ("default");

  // The following two calls are not needed since CS_ZBUF_USE and
  // Object render priority are the default but they show how you
  // can do this.
  //sprite->SetZBufMode (CS_ZBUF_USE);
  //sprite->SetRenderPriority (engine->GetObjectRenderPriority ());

  //sprite->DeferUpdateLighting (CS_NLIGHT_STATIC|CS_NLIGHT_DYNAMIC, 10);
  return true;
}

void Simple::Start ()
{
  csDefaultRunLoop (object_reg);
}

/*---------------------------------------------------------------------*
 * Main function
 *---------------------------------------------------------------------*/
int main (int argc, char* argv[])
{
  iObjectRegistry* object_reg = csInitializer::CreateEnvironment (argc, argv);

  simple = new Simple (object_reg);
  if (simple->Initialize ())
    simple->Start ();
  delete simple;

  csInitializer::DestroyApplication (object_reg);
  return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: astenum.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2004-03-30 16:45:15 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _IDLC_ASTENUM_HXX_
#include <idlc/astenum.hxx>
#endif

#include "registry/version.h"
#include "registry/writer.hxx"

using namespace ::rtl;

AstEnum::AstEnum(const ::rtl::OString& name, AstScope* pScope)
    : AstType(NT_enum, name, pScope)
    , AstScope(NT_enum)
    , m_enumValueCount(0)
{
}

AstEnum::~AstEnum()
{
}

AstConstant* AstEnum::checkValue(AstExpression* pExpr)
{
    DeclList::const_iterator iter = getIteratorBegin();
    DeclList::const_iterator end = getIteratorEnd();
    AstConstant*        pConst = NULL;
    AstDeclaration*     pDecl = NULL;

    while ( iter != end)
    {
        pDecl = *iter;
        pConst = (AstConstant*)pDecl;

        if (pConst->getConstValue()->compare(pExpr))
            return pConst;

        ++iter;
    }

    if ( pExpr->getExprValue()->u.lval > m_enumValueCount )
        m_enumValueCount = pExpr->getExprValue()->u.lval + 1;

    return NULL;
}

sal_Bool AstEnum::dump(RegistryKey& rKey)
{
    RegistryKey localKey;
    if (rKey.createKey( OStringToOUString(getFullName(), RTL_TEXTENCODING_UTF8 ), localKey))
    {
        fprintf(stderr, "%s: warning, could not create key '%s' in '%s'\n",
                idlc()->getOptions()->getProgramName().getStr(),
                getFullName().getStr(), OUStringToOString(rKey.getRegistryName(), RTL_TEXTENCODING_UTF8).getStr());
        return sal_False;
    }

    sal_uInt16 nConst = getNodeCount(NT_enum_val);
    if ( nConst > 0 )
    {
        typereg::Writer aBlob(
            TYPEREG_VERSION_0, getDocumentation(),
            OStringToOUString(getFileName(), RTL_TEXTENCODING_UTF8),
            RT_TYPE_ENUM,
            OStringToOUString(getRelativName(), RTL_TEXTENCODING_UTF8), 0,
            nConst, 0, 0);

        DeclList::const_iterator iter = getIteratorBegin();
        DeclList::const_iterator end = getIteratorEnd();
        AstDeclaration* pDecl = NULL;
        sal_uInt16 index = 0;
        while ( iter != end )
        {
            pDecl = *iter;
            if ( pDecl->getNodeType() == NT_enum_val )
                ((AstConstant*)pDecl)->dumpBlob(aBlob, index++);

            ++iter;
        }

        sal_uInt32 aBlobSize;
        void const * pBlob = aBlob.getBlob(&aBlobSize);

        if (localKey.setValue(OUString(), RG_VALUETYPE_BINARY,
                                (RegValue)pBlob, aBlobSize))
        {
            fprintf(stderr, "%s: warning, could not set value of key \"%s\" in %s\n",
                    idlc()->getOptions()->getProgramName().getStr(),
                    getFullName().getStr(), OUStringToOString(localKey.getRegistryName(), RTL_TEXTENCODING_UTF8).getStr());
            return sal_False;
        }
    }

    return sal_True;
}

AstDeclaration* AstEnum::addDeclaration(AstDeclaration* pDecl)
{
    AstScope* pScope = getScope();
    // add enum value to enclosing scope of the enum
//  pDecl->setName(scopeAsDecl(pScope)->getScopedName() + "::" + pDecl->getLocalName());
//  pScope->addDeclaration(pDecl);

    return AstScope::addDeclaration(pDecl);
}
<commit_msg>INTEGRATION: CWS sb18 (1.4.4); FILE MERGED 2004/05/18 15:36:49 sb 1.4.4.1: #i21150# Added new feature: published.<commit_after>/*************************************************************************
 *
 *  $RCSfile: astenum.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-03 15:07:46 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _IDLC_ASTENUM_HXX_
#include <idlc/astenum.hxx>
#endif

#include "registry/version.h"
#include "registry/writer.hxx"

using namespace ::rtl;

AstEnum::AstEnum(const ::rtl::OString& name, AstScope* pScope)
    : AstType(NT_enum, name, pScope)
    , AstScope(NT_enum)
    , m_enumValueCount(0)
{
}

AstEnum::~AstEnum()
{
}

AstConstant* AstEnum::checkValue(AstExpression* pExpr)
{
    DeclList::const_iterator iter = getIteratorBegin();
    DeclList::const_iterator end = getIteratorEnd();
    AstConstant*        pConst = NULL;
    AstDeclaration*     pDecl = NULL;

    while ( iter != end)
    {
        pDecl = *iter;
        pConst = (AstConstant*)pDecl;

        if (pConst->getConstValue()->compare(pExpr))
            return pConst;

        ++iter;
    }

    if ( pExpr->getExprValue()->u.lval > m_enumValueCount )
        m_enumValueCount = pExpr->getExprValue()->u.lval + 1;

    return NULL;
}

sal_Bool AstEnum::dump(RegistryKey& rKey)
{
    RegistryKey localKey;
    if (rKey.createKey( OStringToOUString(getFullName(), RTL_TEXTENCODING_UTF8 ), localKey))
    {
        fprintf(stderr, "%s: warning, could not create key '%s' in '%s'\n",
                idlc()->getOptions()->getProgramName().getStr(),
                getFullName().getStr(), OUStringToOString(rKey.getRegistryName(), RTL_TEXTENCODING_UTF8).getStr());
        return sal_False;
    }

    sal_uInt16 nConst = getNodeCount(NT_enum_val);
    if ( nConst > 0 )
    {
        typereg::Writer aBlob(
            m_bPublished ? TYPEREG_VERSION_1 : TYPEREG_VERSION_0,
            getDocumentation(),
            OStringToOUString(getFileName(), RTL_TEXTENCODING_UTF8),
            RT_TYPE_ENUM, m_bPublished,
            OStringToOUString(getRelativName(), RTL_TEXTENCODING_UTF8), 0,
            nConst, 0, 0);

        DeclList::const_iterator iter = getIteratorBegin();
        DeclList::const_iterator end = getIteratorEnd();
        AstDeclaration* pDecl = NULL;
        sal_uInt16 index = 0;
        while ( iter != end )
        {
            pDecl = *iter;
            if ( pDecl->getNodeType() == NT_enum_val )
                ((AstConstant*)pDecl)->dumpBlob(aBlob, index++, false);

            ++iter;
        }

        sal_uInt32 aBlobSize;
        void const * pBlob = aBlob.getBlob(&aBlobSize);

        if (localKey.setValue(OUString(), RG_VALUETYPE_BINARY,
                                (RegValue)pBlob, aBlobSize))
        {
            fprintf(stderr, "%s: warning, could not set value of key \"%s\" in %s\n",
                    idlc()->getOptions()->getProgramName().getStr(),
                    getFullName().getStr(), OUStringToOString(localKey.getRegistryName(), RTL_TEXTENCODING_UTF8).getStr());
            return sal_False;
        }
    }

    return sal_True;
}

AstDeclaration* AstEnum::addDeclaration(AstDeclaration* pDecl)
{
    AstScope* pScope = getScope();
    // add enum value to enclosing scope of the enum
//  pDecl->setName(scopeAsDecl(pScope)->getScopedName() + "::" + pDecl->getLocalName());
//  pScope->addDeclaration(pDecl);

    return AstScope::addDeclaration(pDecl);
}
<|endoftext|>


<commit_before>
// Copyright (c) 2013 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "openMVG/image/image.hpp"
#include "openMVG/numeric/numeric.h"

#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include "third_party/progress/progress.hpp"

#include <string>
#include <iostream>

using namespace openMVG;
using namespace std;

// A simple container and undistort function for the Brown's distortion model [1]
// Variables:
// (x,y): 2D point in the image (pixel)
// (u,v): the undistorted 2D point (pixel)
// radial_distortion (k1, k2, k3, ...): vector containing the radial distortion
// (cx,cy): camera principal point
// tangential factors are not considered here
//
// Equation:
// u = x + (x - cx) * (k1 * r^2 + k2 * r^4 +...)
// v = y + (y - cy) * (k1 * r^2 + k2 * r^4 +...)
//
// [1] Decentering distortion of lenses.
//      Brown, Duane C
//      Photometric Engineering 1966
struct BrownDistoModel
{
  Vec2 m_disto_center; // distortion center
  Vec m_radial_distortion; // radial distortion factor
  double m_f; // focal

  inline void ComputeUndistortedCoordinates( double xu, double yu, double &xd, double& yd) const
  {
    Vec2 point (xu, yu);
    Vec2 principal_point (m_disto_center);
    Vec2 point_centered = point - principal_point;

    double u = point_centered.x() / m_f;
    double v = point_centered.y() / m_f;
    double radius_squared = u * u + v * v;

    double coef_radial = 0.0;
    for (int i = m_radial_distortion.size() - 1; i >= 0; --i) {
      coef_radial = (coef_radial + m_radial_distortion[i]) * radius_squared;
    }

    Vec2 undistorted_point = point + point_centered * coef_radial;
    xd = undistorted_point(0);
    yd = undistorted_point(1);
  }
};

/// Undistort an image according a given Distortion model
template <typename Image>
Image undistortImage(
  const Image& I,
  const BrownDistoModel& d,
  RGBColor fillcolor = BLACK,
  bool bcenteringPPpoint = true)
{
  int w = I.Width();
  int h = I.Height();
  double cx = w * .5, cy = h * .5;
  Vec2 offset(0,0);
  if (bcenteringPPpoint)
    offset = Vec2(cx,cy) - d.m_disto_center;

  Image J ( w,h );
  double xu, yu, xd,yd;
  for ( int j=0; j<h; j++ ) {
    for ( int i=0; i<w; i++ ) {
      xu = double (i);
      yu = double (j);
      d.ComputeUndistortedCoordinates(xu, yu, xd, yd);
      xd -= offset(0);
      yd -= offset(1);
      if ( !J.Contains(yd, xd) )
        J ( j,i ) = fillcolor;
      else
        J ( j,i ) = SampleLinear(I, yd, xd);
    }
  }
  return J;
}

int main(int argc, char **argv)
{
  CmdLine cmd;

  std::string sPath;
  std::string sOutPath;
  // Temp storage for the Brown's distortion model
  Vec2 c; // distortion center
  Vec3 k; // distortion factor
  double f; // Focal

  cmd.add( make_option('i', sPath, "imadir") );
  cmd.add( make_option('o', sOutPath, "outdir") );
  cmd.add( make_option('a', c(0), "cx") );
  cmd.add( make_option('b', c(1), "cy") );
  cmd.add( make_option('c', k(0), "k1") );
  cmd.add( make_option('d', k(1), "k2") );
  cmd.add( make_option('e', k(2), "k3") );
  cmd.add( make_option('f', f, "f") );

  try {
      if (argc == 1) throw std::string("Invalid command line parameter.");
      cmd.process(argc, argv);
  } catch(const std::string& s) {
      std::cerr << "Usage: " << argv[0] << ' '
      << "[-i|--imadir path] "
      << "[-o|--outdir path] "
      << std::endl;

      std::cerr << s << std::endl;
      return EXIT_FAILURE;
  }

  if (sOutPath == sPath)
  {
    std::cerr << "Input and Ouput path are set to the same value" << std::endl;
    return EXIT_FAILURE;
  }

  if (!stlplus::folder_exists(sOutPath))
    stlplus::folder_create(sOutPath);

  BrownDistoModel distoModel;
  distoModel.m_disto_center = Vec2(c(0), c(1));
  distoModel.m_radial_distortion = k;
  distoModel.m_f = f;

  std::cout << "Used Brown's distortion model values: \n"
    << "  Distortion center: " << distoModel.m_disto_center.transpose() << "\n"
    << "  Distortion coefficients (K1,K2,K3): "
    << distoModel.m_radial_distortion.transpose() << "\n"
    << "  Distortion focal: " << distoModel.m_f << std::endl;

  std::vector<std::string> vec_fileNames = stlplus::folder_wildcard(sPath, "*.tiff", false, true);

  Image<unsigned char > image, imageU;
  C_Progress_display my_progress_bar( vec_fileNames.size() );
  for (size_t j = 0; j < vec_fileNames.size(); ++j, ++my_progress_bar)
  {
    ReadImage((sPath + "/" + vec_fileNames[j]).c_str(), &image);
    imageU = undistortImage ( image, distoModel);
    string sOutFileName = stlplus::create_filespec(sOutPath, stlplus::basename_part(vec_fileNames[j]), "JPG");
    WriteImage(sOutFileName.c_str(), imageU);
  }

  return EXIT_SUCCESS;
}

<commit_msg>enabled loading of arbitrary images in undistoBrown.cpp<commit_after>
// Copyright (c) 2013 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "openMVG/image/image.hpp"
#include "openMVG/numeric/numeric.h"

#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include "third_party/progress/progress.hpp"

#include <string>
#include <iostream>

using namespace openMVG;
using namespace std;

// A simple container and undistort function for the Brown's distortion model [1]
// Variables:
// (x,y): 2D point in the image (pixel)
// (u,v): the undistorted 2D point (pixel)
// radial_distortion (k1, k2, k3, ...): vector containing the radial distortion
// (cx,cy): camera principal point
// tangential factors are not considered here
//
// Equation:
// u = x + (x - cx) * (k1 * r^2 + k2 * r^4 +...)
// v = y + (y - cy) * (k1 * r^2 + k2 * r^4 +...)
//
// [1] Decentering distortion of lenses.
//      Brown, Duane C
//      Photometric Engineering 1966
struct BrownDistoModel
{
  Vec2 m_disto_center; // distortion center
  Vec m_radial_distortion; // radial distortion factor
  double m_f; // focal

  inline void ComputeUndistortedCoordinates( double xu, double yu, double &xd, double& yd) const
  {
    Vec2 point (xu, yu);
    Vec2 principal_point (m_disto_center);
    Vec2 point_centered = point - principal_point;

    double u = point_centered.x() / m_f;
    double v = point_centered.y() / m_f;
    double radius_squared = u * u + v * v;

    double coef_radial = 0.0;
    for (int i = m_radial_distortion.size() - 1; i >= 0; --i) {
      coef_radial = (coef_radial + m_radial_distortion[i]) * radius_squared;
    }

    Vec2 undistorted_point = point + point_centered * coef_radial;
    xd = undistorted_point(0);
    yd = undistorted_point(1);
  }
};

/// Undistort an image according a given Distortion model
template <typename Image>
Image undistortImage(
  const Image& I,
  const BrownDistoModel& d,
  RGBColor fillcolor = BLACK,
  bool bcenteringPPpoint = true)
{
  int w = I.Width();
  int h = I.Height();
  double cx = w * .5, cy = h * .5;
  Vec2 offset(0,0);
  if (bcenteringPPpoint)
    offset = Vec2(cx,cy) - d.m_disto_center;

  Image J ( w,h );
  double xu, yu, xd,yd;
  for ( int j=0; j<h; j++ ) {
    for ( int i=0; i<w; i++ ) {
      xu = double (i);
      yu = double (j);
      d.ComputeUndistortedCoordinates(xu, yu, xd, yd);
      xd -= offset(0);
      yd -= offset(1);
      if ( !J.Contains(yd, xd) )
        J ( j,i ) = fillcolor;
      else
        J ( j,i ) = SampleLinear(I, yd, xd);
    }
  }
  return J;
}

int main(int argc, char **argv)
{
  CmdLine cmd;

  std::string sPath;
  std::string sOutPath;
  // Temp storage for the Brown's distortion model
  Vec2 c; // distortion center
  Vec3 k; // distortion factor
  double f; // Focal
  int colorMode=0; //0: RGB, 1: Greyscale
  std::string suffix="JPG";

  cmd.add( make_option('i', sPath, "imadir") );
  cmd.add( make_option('o', sOutPath, "outdir") );
  cmd.add( make_option('a', c(0), "cx") );
  cmd.add( make_option('b', c(1), "cy") );
  cmd.add( make_option('c', k(0), "k1") );
  cmd.add( make_option('d', k(1), "k2") );
  cmd.add( make_option('e', k(2), "k3") );
  cmd.add( make_option('f', f, "focal") );
  cmd.add( make_option('s', suffix, "suffix") );

  try {
      if (argc == 1) throw std::string("Invalid command line parameter.");
      cmd.process(argc, argv);
  } catch(const std::string& s) {
      std::cerr << "Usage: " << argv[0] << ' '
      << "[-i|--imadir - Input path]"
      << "[-o|--outdir - path for the undistorted JPG files]"
      << "[-f|--focal - focal length]"
      << "[-s|--suffix - Suffix of the input files. (default: JPG)]"
      << std::endl;

      std::cerr << s << std::endl;
      return EXIT_FAILURE;
  }

  if (sOutPath == sPath)
  {
    std::cerr << "Input and Ouput path are set to the same value" << std::endl;
    return EXIT_FAILURE;
  }

  if (!stlplus::folder_exists(sOutPath))
    stlplus::folder_create(sOutPath);

  BrownDistoModel distoModel;
  distoModel.m_disto_center = Vec2(c(0), c(1));
  distoModel.m_radial_distortion = k;
  distoModel.m_f = f;

  std::cout << "Used Brown's distortion model values: \n"
    << "  Distortion center: " << distoModel.m_disto_center.transpose() << "\n"
    << "  Distortion coefficients (K1,K2,K3): "
    << distoModel.m_radial_distortion.transpose() << "\n"
    << "  Distortion focal: " << distoModel.m_f << std::endl;

  std::vector<std::string> vec_fileNames = stlplus::folder_wildcard(sPath, "*."+suffix, false, true);
  std::cout << "\nLocated " << vec_fileNames.size() << " files in " << sPath << " with suffix " << suffix;

    Image<unsigned char > imageGreyIn, imageGreyU;
    Image<RGBColor> imageRGBIn, imageRGBU;
    Image<RGBAColor> imageRGBAIn, imageRGBAU;

    C_Progress_display my_progress_bar( vec_fileNames.size() );
    for (size_t j = 0; j < vec_fileNames.size(); ++j, ++my_progress_bar)
    {
      //read the depth
      int w,h,depth;
      vector<unsigned char> tmp_vec;
      string sOutFileName = stlplus::create_filespec(sOutPath, stlplus::basename_part(vec_fileNames[j]), "JPG");
      int res = ReadImage((sPath + "/" + vec_fileNames[j]).c_str(), &tmp_vec, &w, &h, &depth);
      if (res == 1)
      {
        switch(depth)
        {
          case 1: //Greyscale
            {
              imageGreyIn = Eigen::Map<Image<unsigned char>::Base>(&tmp_vec[0], h, w);
              imageGreyIn=Eigen::Map<Image<unsigned char>::Base>(&tmp_vec[0], h, w);
              imageGreyU = undistortImage ( imageGreyIn, distoModel);
              WriteImage(sOutFileName.c_str(), imageGreyU);
              break;
            }
          case 3: //RGB
            {
              RGBColor * ptrCol = (RGBColor*) &tmp_vec[0];
              imageRGBIn = Eigen::Map<Image<RGBColor>::Base>(ptrCol, h, w);
              //convert RGB to gray
              //ConvertPixelType(imageRGBIn, &tmp_vec );
              imageRGBU = undistortImage ( imageRGBIn, distoModel);
              WriteImage(sOutFileName.c_str(), imageRGBU);
              break;
            }
          case 4: //RGBA
            {
              RGBAColor * ptrCol = (RGBAColor*) &tmp_vec[0];
              imageRGBAIn = Eigen::Map<Image<RGBAColor>::Base>(ptrCol, h, w);
              //convert RGBA to gray
              //ConvertPixelType(imageRGBAIn, &tmp_vec);
              imageRGBAU = undistortImage ( imageRGBAIn, distoModel);
              WriteImage(sOutFileName.c_str(), imageRGBAU);
              break;
            }
        }

      }//end if res==1
      else
      {
        std::cerr << "\nThe image contains " << depth << "layers. This depth is not supported!";
      }
  } //end loop for each file
  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>/*
Copyright (c) 2017 InversePalindrome
Nihil - AIComponent.hpp
InversePalindrome.com
*/

#pragma once

#include "Component.hpp"

#include <SFML/System/Vector2.hpp>

#include <utility>

class AIComponent : public Component
{
	friend std::ostream& operator<<(std::ostream& os, const AIComponent& component);
	using Path = std::pair<float, float>;

public:
	AIComponent(float visionRange, float initialX, float finalX);

	float getVisionRange() const;
	Path getPath() const;

	void setVisionRange(float visionRange);
	void setPath(const Path& path);

	void swapPathPoints();

private:
	float visionRange;
    Path path;
};

std::ostream& operator<<(std::ostream& os, const AIComponent& component);

<commit_msg>Delete AIComponent.hpp<commit_after><|endoftext|>


<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.

Bohrium 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 3
of the License, or (at your option) any later version.

Bohrium 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 Lesser General Public License along with Bohrium.

If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef __BH_CONSTANT_H
#define __BH_CONSTANT_H

#include <iostream>

#include <bh_type.hpp>

union bh_constant_value
{
    bh_bool       bool8;
    bh_int8       int8;
    bh_int16      int16;
    bh_int32      int32;
    bh_int64      int64;
    bh_uint8      uint8;
    bh_uint16     uint16;
    bh_uint32     uint32;
    bh_uint64     uint64;
    bh_float32    float32;
    bh_float64    float64;
    bh_complex64  complex64;
    bh_complex128 complex128;
    bh_r123       r123;
};

struct bh_constant
{
    bh_constant_value value;
    bh_type type;

    //Convert the constant value to an int64
    //Throw an overflow_error() exception if impossible
    int64_t get_int64() const;

    //Convert the constant value to an uint64
    //Throw an overflow_error() exception if impossible
    uint64_t get_uint64() const;

    //Convert the constant value to an double
    //Throw an overflow_error() exception if impossible
    //Throw an runtime_error() exception if type is unknown
    double get_double() const;

    //Set the constant based on value
    //Throw an overflow_error() exception if impossible
    //Throw an runtime_error() exception if type is unknown
    void set_double(double value);

    bool operator==(const bh_constant& other) const;

    bool operator!=(const bh_constant& other) const
    {
        return !(other == *this);
    }
    //Implements pprint of a constant
    // Set 'opencl' for OpenCL specific output
    void pprint(std::ostream& out, bool opencl=false) const;
};

//Implements pprint of a constant (by streaming)
DLLEXPORT std::ostream& operator<<(std::ostream& out, const bh_constant& constant);

#endif
<commit_msg>Implemented a constructor for bh_constant<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.

Bohrium 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 3
of the License, or (at your option) any later version.

Bohrium 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 Lesser General Public License along with Bohrium.

If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef __BH_CONSTANT_H
#define __BH_CONSTANT_H

#include <iostream>
#include <bh_type.hpp>

union bh_constant_value
{
    bh_bool       bool8;
    bh_int8       int8;
    bh_int16      int16;
    bh_int32      int32;
    bh_int64      int64;
    bh_uint8      uint8;
    bh_uint16     uint16;
    bh_uint32     uint32;
    bh_uint64     uint64;
    bh_float32    float32;
    bh_float64    float64;
    bh_complex64  complex64;
    bh_complex128 complex128;
    bh_r123       r123;

    // Constructors for each possible union type
    bh_constant_value() = default;
    bh_constant_value(bool val) : bool8(val) {}
    bh_constant_value(int8_t val) : int8(val) {}
    bh_constant_value(int16_t val) : int16(val) {}
    bh_constant_value(int32_t val) : int32(val) {}
    bh_constant_value(int64_t val) : int64(val) {}
    bh_constant_value(uint8_t val) : uint8(val) {}
    bh_constant_value(uint16_t val) : uint16(val) {}
    bh_constant_value(uint32_t val) : uint32(val) {}
    bh_constant_value(uint64_t val) : uint64(val) {}
    bh_constant_value(float val) : float32(val) {}
    bh_constant_value(double val) : float64(val) {}
    bh_constant_value(std::complex<float> val) : complex64{val.real(), val.imag()} {}
    bh_constant_value(std::complex<double> val) : complex128{val.real(), val.imag()} {}
    bh_constant_value(bh_r123 val) : r123(val) {}
};

class bh_constant
{
public:
    bh_constant_value value;
    bh_type type;

    bh_constant() = default;

    //Constructor based on type
    template<typename T>
    bh_constant(T val) : value(val), type(bh_type_from_template<T>()){}

    //Convert the constant value to an int64
    //Throw an overflow_error() exception if impossible
    int64_t get_int64() const;

    //Convert the constant value to an uint64
    //Throw an overflow_error() exception if impossible
    uint64_t get_uint64() const;

    //Convert the constant value to an double
    //Throw an overflow_error() exception if impossible
    //Throw an runtime_error() exception if type is unknown
    double get_double() const;

    //Set the constant based on value
    //Throw an overflow_error() exception if impossible
    //Throw an runtime_error() exception if type is unknown
    void set_double(double value);

    bool operator==(const bh_constant& other) const;

    bool operator!=(const bh_constant& other) const
    {
        return !(other == *this);
    }
    //Implements pprint of a constant
    // Set 'opencl' for OpenCL specific output
    void pprint(std::ostream& out, bool opencl=false) const;
};

//Implements pprint of a constant (by streaming)
DLLEXPORT std::ostream& operator<<(std::ostream& out, const bh_constant& constant);

#endif
<|endoftext|>