<commit_before>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__

#include <vw/BundleAdjustment/ControlNetwork.h>
#include <vw/BundleAdjustment/CameraRelation.h>
#include <vw/Cartography.h>
using namespace vw;
using namespace vw::ba;
using namespace vw::camera;

#include <boost/algorithm/string.hpp>
#include <boost/program_options.hpp>
#include <boost/foreach.hpp>
#include <boost/filesystem/path.hpp>
namespace po = boost::program_options;
namespace fs = boost::filesystem;

#include <asp/IsisIO/IsisCameraModel.h>
#include <asp/Core/Macros.h>

int find_destination_index( int const& source_idx,
                            std::map<int,std::string> const& src_map,
                            std::map<std::string,int> & dst_map,
                            int & dst_max_idx ) {
  std::map<std::string,int>::iterator search =
    dst_map.find( src_map.find(source_idx)->second );
  int dst_index;
  if ( search == dst_map.end() ) {
    dst_max_idx++;
    dst_index = dst_max_idx;
    std::string serial = src_map.find(source_idx)->second;
    vw_out() << "  Adding camera w/ serial: " << serial << "\n";
    dst_map[ serial ] = dst_index;
  } else {
    dst_index = search->second;
  }
  return dst_index;
}

void print_cnet_statistics( ControlNetwork const& cnet ) {
  int cmeasure_size = 0;
  BOOST_FOREACH( ControlPoint const& cp, cnet ) {
    cmeasure_size+=cp.size();
  }
  vw_out() << "  CP : " << cnet.size() << "   CM : " << cmeasure_size << "\n";
}

struct ContainsEqualMeasure {
  Vector2 m_position;
  ContainsEqualMeasure( Vector2 const& pos ) : m_position(pos) {}

  bool operator()( boost::shared_ptr<IPFeature> in ) {
    if ( m_position[0] == in->m_ip.x &&
         m_position[1] == in->m_ip.y )
      return true;
    return false;
  }
};

struct ContainsCloseMeasure {
  Vector2 m_position;
  double m_close;
  ContainsCloseMeasure( Vector2 const& pos, double const& close ) : m_position(pos), m_close(close) {}

  bool operator()( boost::shared_ptr<IPFeature> in ) {
    if ( norm_2( Vector2(in->m_ip.x, in->m_ip.y) - m_position ) <= m_close )
      return true;
    return false;
  }
};

struct Options {
  // Input
  std::string destination_cnet;
  std::vector<std::string> source_cnets;

  double close;

  // Output
  std::string output_prefix;
};

void handle_arguments( int argc, char *argv[], Options& opt ) {
  po::options_description general_options("");
  general_options.add_options()
    ("output-prefix,o", po::value(&opt.output_prefix)->default_value("merged"),
     "Output prefix for merge control network.")
    ("close-px", po::value(&opt.close)->default_value(-1),
     "Merge measurements are that are this pixel close. Leave -1 to only merge exact measurements." )
    ("help,h", "Display this help message");

  po::options_description positional("");
  positional.add_options()
    ("dest-cnet", po::value(&opt.destination_cnet) )
    ("source-cnets", po::value(&opt.source_cnets) );

  po::positional_options_description positional_desc;
  positional_desc.add("dest-cnet", 1 );
  positional_desc.add("source-cnets", -1 );

  po::options_description all_options;
  all_options.add(general_options).add(positional);

  po::variables_map vm;
  try {
    po::store( po::command_line_parser( argc, argv ).options(all_options).positional(positional_desc).run(), vm );
    po::notify( vm );
  } catch (po::error &e) {
    vw_throw( ArgumentErr() << "Error parsing input:\n\t"
              << e.what() << general_options );
  }

  std::ostringstream usage;
  usage << "Usage: " << argv[0] << " [options] <dest> <source1> ... <sourceN>\n";

  if ( vm.count("help") )
    vw_throw( ArgumentErr() << usage.str() << general_options );
  if ( opt.destination_cnet.empty() )
    vw_throw( ArgumentErr() << "Missing destination cnets.\n"
              << usage.str() << general_options );
  if ( opt.source_cnets.empty() )
    vw_throw( ArgumentErr() << "Missing source cnets.\n"
              << usage.str() << general_options );
}

int main( int argc, char** argv ) {

  Options opt;
  try {
    handle_arguments( argc, argv, opt );

    ControlNetwork dst_cnet("destination");
    dst_cnet.read_binary( opt.destination_cnet );

    vw_out() << "Destination Control Network:\n";
    print_cnet_statistics( dst_cnet );

    std::map<std::string,int> dst_serial_to_cam_idx;
    int dst_max_cam_idx = -1;
    {
      float inc_amt = 1.0/float(dst_cnet.size());
      TerminalProgressCallback tpc("","Destination Idx:");
      BOOST_FOREACH( ControlPoint const& cp, dst_cnet ) {
        tpc.report_incremental_progress( inc_amt );
        BOOST_FOREACH( ControlMeasure const& cm, cp ) {
          if ( dst_serial_to_cam_idx.find( cm.serial() ) ==
               dst_serial_to_cam_idx.end() ) {
            dst_serial_to_cam_idx[cm.serial()] = cm.image_id();
            if ( cm.image_id() > dst_max_cam_idx )
              dst_max_cam_idx = cm.image_id();
          }
        }
      }
      tpc.report_finished();
    }
    vw_out() << "Input Control Network has " << dst_max_cam_idx+1 << " cameras.\n";

    CameraRelationNetwork<IPFeature> dst_crn;
    dst_crn.read_controlnetwork( dst_cnet );

    BOOST_FOREACH( std::string const& source_cnet, opt.source_cnets ) {
      ControlNetwork src_cnet("source");
      src_cnet.read_binary( source_cnet );

      vw_out() << "Input " << source_cnet << ":\n";
      print_cnet_statistics( src_cnet );

      typedef std::map<int,std::string> src_map_type;
      src_map_type src_cam_idx_to_serial;
      float inc_amt = 1.0/float(src_cnet.size());
      {
        TerminalProgressCallback tpc("cnet",source_cnet+" Idx:");
        BOOST_FOREACH( ControlPoint const& cp, src_cnet ) {
          tpc.report_incremental_progress( inc_amt );
          BOOST_FOREACH( ControlMeasure const& cm, cp ) {
            if ( src_cam_idx_to_serial.find( cm.image_id() ) ==
                 src_cam_idx_to_serial.end() )
              src_cam_idx_to_serial[cm.image_id()] = cm.serial();
          }
        }
        tpc.report_finished();
      }

      {
        TerminalProgressCallback tpc("cnet",source_cnet+" Merge:");
        BOOST_FOREACH( ControlPoint const& cp, src_cnet ) {
          tpc.report_incremental_progress(inc_amt );

          typedef boost::shared_ptr<IPFeature> f_ptr;
          typedef std::list<f_ptr>::iterator f_itr;

          ControlPoint::const_iterator cm1, cm2;
          cm1 = cm2 = cp.begin();
          cm2++;
          int dst_index1 =
            find_destination_index( cm1->image_id(),
                                    src_cam_idx_to_serial,
                                    dst_serial_to_cam_idx,
                                    dst_max_cam_idx );
          f_itr dst_feature1;
          if ( opt.close < 0 ) {
            dst_feature1 = std::find_if( dst_crn[dst_index1].begin(),
                                         dst_crn[dst_index1].end(),
                                         ContainsEqualMeasure(cm1->position()));
          } else {
            dst_feature1 = std::find_if( dst_crn[dst_index1].begin(),
                                         dst_crn[dst_index1].end(),
                                         ContainsCloseMeasure(cm1->position(),opt.close));
          }
          if ( dst_feature1 == dst_crn[dst_index1].end() ) {
            dst_crn[dst_index1].relations.push_front( f_ptr( new IPFeature(*cm1,0, dst_index1) ));
            dst_feature1 = dst_crn[dst_index1].begin();
          }
          while ( cm2 != cp.end() ) {
            int dst_index2 =
              find_destination_index( cm2->image_id(),
                                      src_cam_idx_to_serial,
                                      dst_serial_to_cam_idx,
                                      dst_max_cam_idx );
            f_itr dst_feature2;
            if ( opt.close < 0 ) {
              dst_feature2 = std::find_if( dst_crn[dst_index2].begin(),
                                           dst_crn[dst_index2].end(),
                                           ContainsEqualMeasure(cm2->position()));
            } else {
              dst_feature2 = std::find_if( dst_crn[dst_index2].begin(),
                                           dst_crn[dst_index2].end(),
                                           ContainsCloseMeasure(cm2->position(),opt.close));
            }
            if ( dst_feature2 == dst_crn[dst_index2].end() ) {
              dst_crn[dst_index2].relations.push_front( f_ptr( new IPFeature( *cm2, 0, dst_index2 )));
              dst_feature2 = dst_crn[dst_index2].begin();
            }

            // Doubly linking
            (*dst_feature1)->connection( *dst_feature2, true );
            (*dst_feature2)->connection( *dst_feature1, true );

            dst_index1 = dst_index2;
            dst_feature1 = dst_feature2;
            cm1++; cm2++;
          }
        }
        tpc.report_finished();
      }
    }

    dst_crn.write_controlnetwork( dst_cnet );
    vw_out() << "Output Control Network:\n";
    print_cnet_statistics( dst_cnet );

    // Re apply serial
    std::map<int,std::string> reverse_dst;
    for ( std::map<std::string,int>::iterator it = dst_serial_to_cam_idx.begin();
          it != dst_serial_to_cam_idx.end(); it++ ) {
      reverse_dst[it->second] = it->first;
    }
    BOOST_FOREACH( ControlPoint & cp, dst_cnet ) {
      BOOST_FOREACH( ControlMeasure & cm, cp ) {
        cm.set_serial( reverse_dst[cm.image_id()] );
      }
    }

    dst_cnet.write_binary(opt.output_prefix);

  } ASP_STANDARD_CATCHES;
}
<commit_msg>Allow cnet_merge to add cameras<commit_after>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__

#include <vw/BundleAdjustment/ControlNetwork.h>
#include <vw/BundleAdjustment/CameraRelation.h>
#include <vw/Cartography.h>
using namespace vw;
using namespace vw::ba;
using namespace vw::camera;

#include <boost/algorithm/string.hpp>
#include <boost/program_options.hpp>
#include <boost/foreach.hpp>
#include <boost/filesystem/path.hpp>
namespace po = boost::program_options;
namespace fs = boost::filesystem;

#include <asp/IsisIO/IsisCameraModel.h>
#include <asp/Core/Macros.h>

int find_destination_index( int const& source_idx,
                            std::map<int,std::string> const& src_map,
                            std::map<std::string,int> & dst_map,
                            int & dst_max_idx ) {
  std::map<std::string,int>::iterator search =
    dst_map.find( src_map.find(source_idx)->second );
  int dst_index;
  if ( search == dst_map.end() ) {
    dst_max_idx++;
    dst_index = dst_max_idx;
    std::string serial = src_map.find(source_idx)->second;
    vw_out() << "  Adding camera w/ serial: " << serial << "\n";
    dst_map[ serial ] = dst_index;
  } else {
    dst_index = search->second;
  }
  return dst_index;
}

void print_cnet_statistics( ControlNetwork const& cnet ) {
  int cmeasure_size = 0;
  BOOST_FOREACH( ControlPoint const& cp, cnet ) {
    cmeasure_size+=cp.size();
  }
  vw_out() << "  CP : " << cnet.size() << "   CM : " << cmeasure_size << "\n";
}

struct ContainsEqualMeasure {
  Vector2 m_position;
  ContainsEqualMeasure( Vector2 const& pos ) : m_position(pos) {}

  bool operator()( boost::shared_ptr<IPFeature> in ) {
    if ( m_position[0] == in->m_ip.x &&
         m_position[1] == in->m_ip.y )
      return true;
    return false;
  }
};

struct ContainsCloseMeasure {
  Vector2 m_position;
  double m_close;
  ContainsCloseMeasure( Vector2 const& pos, double const& close ) : m_position(pos), m_close(close) {}

  bool operator()( boost::shared_ptr<IPFeature> in ) {
    if ( norm_2( Vector2(in->m_ip.x, in->m_ip.y) - m_position ) <= m_close )
      return true;
    return false;
  }
};

struct Options {
  // Input
  std::string destination_cnet;
  std::vector<std::string> source_cnets;

  double close;

  // Output
  std::string output_prefix;
};

void handle_arguments( int argc, char *argv[], Options& opt ) {
  po::options_description general_options("");
  general_options.add_options()
    ("output-prefix,o", po::value(&opt.output_prefix)->default_value("merged"),
     "Output prefix for merge control network.")
    ("close-px", po::value(&opt.close)->default_value(-1),
     "Merge measurements are that are this pixel close. Leave -1 to only merge exact measurements." )
    ("help,h", "Display this help message");

  po::options_description positional("");
  positional.add_options()
    ("dest-cnet", po::value(&opt.destination_cnet) )
    ("source-cnets", po::value(&opt.source_cnets) );

  po::positional_options_description positional_desc;
  positional_desc.add("dest-cnet", 1 );
  positional_desc.add("source-cnets", -1 );

  po::options_description all_options;
  all_options.add(general_options).add(positional);

  po::variables_map vm;
  try {
    po::store( po::command_line_parser( argc, argv ).options(all_options).positional(positional_desc).run(), vm );
    po::notify( vm );
  } catch (po::error &e) {
    vw_throw( ArgumentErr() << "Error parsing input:\n\t"
              << e.what() << general_options );
  }

  std::ostringstream usage;
  usage << "Usage: " << argv[0] << " [options] <dest> <source1> ... <sourceN>\n";

  if ( vm.count("help") )
    vw_throw( ArgumentErr() << usage.str() << general_options );
  if ( opt.destination_cnet.empty() )
    vw_throw( ArgumentErr() << "Missing destination cnets.\n"
              << usage.str() << general_options );
  if ( opt.source_cnets.empty() )
    vw_throw( ArgumentErr() << "Missing source cnets.\n"
              << usage.str() << general_options );
}

int main( int argc, char** argv ) {

  Options opt;
  try {
    handle_arguments( argc, argv, opt );

    ControlNetwork dst_cnet("destination");
    dst_cnet.read_binary( opt.destination_cnet );

    vw_out() << "Destination Control Network:\n";
    print_cnet_statistics( dst_cnet );

    std::map<std::string,int> dst_serial_to_cam_idx;
    int dst_max_cam_idx = -1;
    {
      float inc_amt = 1.0/float(dst_cnet.size());
      TerminalProgressCallback tpc("","Destination Idx:");
      BOOST_FOREACH( ControlPoint const& cp, dst_cnet ) {
        tpc.report_incremental_progress( inc_amt );
        BOOST_FOREACH( ControlMeasure const& cm, cp ) {
          if ( dst_serial_to_cam_idx.find( cm.serial() ) ==
               dst_serial_to_cam_idx.end() ) {
            dst_serial_to_cam_idx[cm.serial()] = cm.image_id();
            if ( cm.image_id() > dst_max_cam_idx )
              dst_max_cam_idx = cm.image_id();
          }
        }
      }
      tpc.report_finished();
    }
    vw_out() << "Input Control Network has " << dst_max_cam_idx+1 << " cameras.\n";

    CameraRelationNetwork<IPFeature> dst_crn;
    dst_crn.read_controlnetwork( dst_cnet );

    BOOST_FOREACH( std::string const& source_cnet, opt.source_cnets ) {
      ControlNetwork src_cnet("source");
      src_cnet.read_binary( source_cnet );

      vw_out() << "Input " << source_cnet << ":\n";
      print_cnet_statistics( src_cnet );

      typedef std::map<int,std::string> src_map_type;
      src_map_type src_cam_idx_to_serial;
      float inc_amt = 1.0/float(src_cnet.size());
      {
        TerminalProgressCallback tpc("cnet",source_cnet+" Idx:");
        BOOST_FOREACH( ControlPoint const& cp, src_cnet ) {
          tpc.report_incremental_progress( inc_amt );
          BOOST_FOREACH( ControlMeasure const& cm, cp ) {
            if ( src_cam_idx_to_serial.find( cm.image_id() ) ==
                 src_cam_idx_to_serial.end() )
              src_cam_idx_to_serial[cm.image_id()] = cm.serial();
          }
        }
        tpc.report_finished();
      }

      {
        TerminalProgressCallback tpc("cnet",source_cnet+" Merge:");
        BOOST_FOREACH( ControlPoint const& cp, src_cnet ) {
          tpc.report_incremental_progress(inc_amt );

          typedef boost::shared_ptr<IPFeature> f_ptr;
          typedef std::list<f_ptr>::iterator f_itr;

          ControlPoint::const_iterator cm1, cm2;
          cm1 = cm2 = cp.begin();
          cm2++;
          int dst_index1 =
            find_destination_index( cm1->image_id(),
                                    src_cam_idx_to_serial,
                                    dst_serial_to_cam_idx,
                                    dst_max_cam_idx );

	  if ( dst_index1 == dst_crn.size() )
	    dst_crn.add_node( CameraNode<IPFeature>(dst_index1,"") );

          f_itr dst_feature1;
          if ( opt.close < 0 ) {
            dst_feature1 = std::find_if( dst_crn[dst_index1].begin(),
                                         dst_crn[dst_index1].end(),
                                         ContainsEqualMeasure(cm1->position()));
          } else {
            dst_feature1 = std::find_if( dst_crn[dst_index1].begin(),
                                         dst_crn[dst_index1].end(),
                                         ContainsCloseMeasure(cm1->position(),opt.close));
          }
          if ( dst_feature1 == dst_crn[dst_index1].end() ) {
            dst_crn[dst_index1].relations.push_front( f_ptr( new IPFeature(*cm1,0, dst_index1) ));
            dst_feature1 = dst_crn[dst_index1].begin();
          }
          while ( cm2 != cp.end() ) {
            int dst_index2 =
              find_destination_index( cm2->image_id(),
                                      src_cam_idx_to_serial,
                                      dst_serial_to_cam_idx,
                                      dst_max_cam_idx );

	    if ( dst_index2 == dst_crn.size() )
	      dst_crn.add_node( CameraNode<IPFeature>(dst_index2,"") );

            f_itr dst_feature2;
            if ( opt.close < 0 ) {
              dst_feature2 = std::find_if( dst_crn[dst_index2].begin(),
                                           dst_crn[dst_index2].end(),
                                           ContainsEqualMeasure(cm2->position()));
            } else {
              dst_feature2 = std::find_if( dst_crn[dst_index2].begin(),
                                           dst_crn[dst_index2].end(),
                                           ContainsCloseMeasure(cm2->position(),opt.close));
            }
            if ( dst_feature2 == dst_crn[dst_index2].end() ) {
              dst_crn[dst_index2].relations.push_front( f_ptr( new IPFeature( *cm2, 0, dst_index2 )));
              dst_feature2 = dst_crn[dst_index2].begin();
            }

            // Doubly linking
            (*dst_feature1)->connection( *dst_feature2, true );
            (*dst_feature2)->connection( *dst_feature1, true );

            dst_index1 = dst_index2;
            dst_feature1 = dst_feature2;
            cm1++; cm2++;
          }
        }
        tpc.report_finished();
      }
    }

    dst_crn.write_controlnetwork( dst_cnet );
    vw_out() << "Output Control Network:\n";
    print_cnet_statistics( dst_cnet );

    // Re apply serial
    std::map<int,std::string> reverse_dst;
    for ( std::map<std::string,int>::iterator it = dst_serial_to_cam_idx.begin();
          it != dst_serial_to_cam_idx.end(); it++ ) {
      reverse_dst[it->second] = it->first;
    }
    BOOST_FOREACH( ControlPoint & cp, dst_cnet ) {
      BOOST_FOREACH( ControlMeasure & cm, cp ) {
        cm.set_serial( reverse_dst[cm.image_id()] );
      }
    }

    dst_cnet.write_binary(opt.output_prefix);

  } ASP_STANDARD_CATCHES;
}
<|endoftext|>


<commit_before>//===- MinGW.cpp ----------------------------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "MinGW.h"
#include "Error.h"
#include "llvm/Object/COFF.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"

using namespace lld;
using namespace lld::coff;
using namespace llvm;
using namespace llvm::COFF;

AutoExporter::AutoExporter() {
  if (Config->Machine == I386)
    ExcludeSymbols = {
        "__NULL_IMPORT_DESCRIPTOR",
        "__pei386_runtime_relocator",
        "_do_pseudo_reloc",
        "_impure_ptr",
        "__impure_ptr",
        "__fmode",
        "_environ",
        "___dso_handle",
        // These are the MinGW names that differ from the standard
        // ones (lacking an extra underscore).
        "_DllMain@12",
        "_DllEntryPoint@12",
        "_DllMainCRTStartup@12",
    };
  else
    ExcludeSymbols = {
        "_NULL_IMPORT_DESCRIPTOR",
        "_pei386_runtime_relocator",
        "do_pseudo_reloc",
        "impure_ptr",
        "_impure_ptr",
        "_fmode",
        "environ",
        "__dso_handle",
        // These are the MinGW names that differ from the standard
        // ones (lacking an extra underscore).
        "DllMain",
        "DllEntryPoint",
        "DllMainCRTStartup",
    };

  ExcludeLibs = {
      "libgcc",
      "libgcc_s",
      "libstdc++",
      "libmingw32",
      "libmingwex",
      "libg2c",
      "libsupc++",
      "libobjc",
      "libgcj",
      "libclang_rt.builtins-aarch64",
      "libclang_rt.builtins-arm",
      "libclang_rt.builtins-i386",
      "libclang_rt.builtins-x86_64",
  };
  ExcludeObjects = {
      "crt0.o",
      "crt1.o",
      "crt1u.o",
      "crt2.o",
      "crt2u.o",
      "dllcrt1.o",
      "dllcrt2.o",
      "gcrt0.o",
      "gcrt1.o",
      "gcrt2.o",
      "crtbegin.o",
      "crtend.o",
  };
}

bool AutoExporter::shouldExport(Defined *Sym) const {
  if (!Sym || !Sym->isLive() || !Sym->getChunk())
    return false;
  if (ExcludeSymbols.count(Sym->getName()))
    return false;
  StringRef LibName = sys::path::filename(Sym->getFile()->ParentName);
  // Drop the file extension.
  LibName = LibName.substr(0, LibName.rfind('.'));
  if (ExcludeLibs.count(LibName))
    return false;
  StringRef FileName = sys::path::filename(Sym->getFile()->getName());
  if (LibName.empty() && ExcludeObjects.count(FileName))
    return false;
  return true;
}

void coff::writeDefFile(StringRef Name) {
  std::error_code EC;
  raw_fd_ostream OS(Name, EC, sys::fs::F_None);
  if (EC)
    fatal("cannot open " + Name + ": " + EC.message());

  OS << "EXPORTS\n";
  for (Export &E : Config->Exports) {
    OS << "    " << E.ExportName << " "
       << "@" << E.Ordinal;
    if (auto *Def = dyn_cast_or_null<Defined>(E.Sym)) {
      if (Def && Def->getChunk() &&
          !(Def->getChunk()->getPermissions() & IMAGE_SCN_MEM_EXECUTE))
        OS << " DATA";
    }
    OS << "\n";
  }
}
<commit_msg>[MinGW] Omit libc++/libc++abi/libunwind from autoexporting<commit_after>//===- MinGW.cpp ----------------------------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "MinGW.h"
#include "Error.h"
#include "llvm/Object/COFF.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"

using namespace lld;
using namespace lld::coff;
using namespace llvm;
using namespace llvm::COFF;

AutoExporter::AutoExporter() {
  if (Config->Machine == I386)
    ExcludeSymbols = {
        "__NULL_IMPORT_DESCRIPTOR",
        "__pei386_runtime_relocator",
        "_do_pseudo_reloc",
        "_impure_ptr",
        "__impure_ptr",
        "__fmode",
        "_environ",
        "___dso_handle",
        // These are the MinGW names that differ from the standard
        // ones (lacking an extra underscore).
        "_DllMain@12",
        "_DllEntryPoint@12",
        "_DllMainCRTStartup@12",
    };
  else
    ExcludeSymbols = {
        "_NULL_IMPORT_DESCRIPTOR",
        "_pei386_runtime_relocator",
        "do_pseudo_reloc",
        "impure_ptr",
        "_impure_ptr",
        "_fmode",
        "environ",
        "__dso_handle",
        // These are the MinGW names that differ from the standard
        // ones (lacking an extra underscore).
        "DllMain",
        "DllEntryPoint",
        "DllMainCRTStartup",
    };

  ExcludeLibs = {
      "libgcc",
      "libgcc_s",
      "libstdc++",
      "libmingw32",
      "libmingwex",
      "libg2c",
      "libsupc++",
      "libobjc",
      "libgcj",
      "libclang_rt.builtins-aarch64",
      "libclang_rt.builtins-arm",
      "libclang_rt.builtins-i386",
      "libclang_rt.builtins-x86_64",
      "libc++",
      "libc++abi",
      "libunwind",
  };
  ExcludeObjects = {
      "crt0.o",
      "crt1.o",
      "crt1u.o",
      "crt2.o",
      "crt2u.o",
      "dllcrt1.o",
      "dllcrt2.o",
      "gcrt0.o",
      "gcrt1.o",
      "gcrt2.o",
      "crtbegin.o",
      "crtend.o",
  };
}

bool AutoExporter::shouldExport(Defined *Sym) const {
  if (!Sym || !Sym->isLive() || !Sym->getChunk())
    return false;
  if (ExcludeSymbols.count(Sym->getName()))
    return false;
  StringRef LibName = sys::path::filename(Sym->getFile()->ParentName);
  // Drop the file extension.
  LibName = LibName.substr(0, LibName.rfind('.'));
  if (ExcludeLibs.count(LibName))
    return false;
  StringRef FileName = sys::path::filename(Sym->getFile()->getName());
  if (LibName.empty() && ExcludeObjects.count(FileName))
    return false;
  return true;
}

void coff::writeDefFile(StringRef Name) {
  std::error_code EC;
  raw_fd_ostream OS(Name, EC, sys::fs::F_None);
  if (EC)
    fatal("cannot open " + Name + ": " + EC.message());

  OS << "EXPORTS\n";
  for (Export &E : Config->Exports) {
    OS << "    " << E.ExportName << " "
       << "@" << E.Ordinal;
    if (auto *Def = dyn_cast_or_null<Defined>(E.Sym)) {
      if (Def && Def->getChunk() &&
          !(Def->getChunk()->getPermissions() & IMAGE_SCN_MEM_EXECUTE))
        OS << " DATA";
    }
    OS << "\n";
  }
}
<|endoftext|>


<commit_before>/*
// License Agreement (3-clause BSD License)
// Copyright (c) 2015, Klaus Haag, all rights reserved.
// Third party copyrights and patents are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * 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 names of the copyright holders nor the names of the 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 copyright holders 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.
*/

#ifndef HELPER_H_
#define HELPER_H_

#include <opencv2/core/core.hpp>

#include "cv_ext.hpp"
#include "mat_consts.hpp"

namespace cf_tracking
{
    void dftCcs(const cv::Mat& input, cv::Mat& out, int flags = 0);
    void dftNoCcs(const cv::Mat& input, cv::Mat& out, int flags = 0);
    int mod(int dividend, int divisor);
    void depResize(const cv::Mat& source, cv::Mat& dst, const cv::Size& dsize);

    template<typename T>
    cv::Size_<T> sizeFloor(cv::Size_<T> size)
    {
        return cv::Size_<T>(floor(size.width), floor(size.height));
    }

    template <typename T>
    cv::Mat numberToRowVector(int n)
    {
        cv::Mat_<T> rowVec(n, 1);

        for (int i = 0; i < n; ++i)
            rowVec.template at<T>(i, 0) = static_cast<T>(i + 1);

        return rowVec;
    }

    template <typename T>
    cv::Mat numberToColVector(int n)
    {
        cv::Mat_<T> colVec(1, n);

        for (int i = 0; i < n; ++i)
            colVec.template at<T>(0, i) = static_cast<T>(i + 1);

        return colVec;
    }

    // http://home.isr.uc.pt/~henriques/circulant/
    template <typename T>
    T subPixelPeak(T* p)
    {
        T delta = mat_consts::constants<T>::c0_5 * (p[2] - p[0]) / (2 * p[1] - p[2] - p[0]);

        if (!std::isfinite(delta))
            return 0;

        return delta;
    }

    // http://home.isr.uc.pt/~henriques/circulant/
    template <typename T>
    cv::Point_<T> subPixelDelta(const cv::Mat& response, const cv::Point2i& delta)
    {
        cv::Point_<T> subDelta(static_cast<float>(delta.x), static_cast<float>(delta.y));
        T vNeighbors[3] = {};
        T hNeighbors[3] = {};

        for (int i = -1; i < 2; ++i)
        {
            vNeighbors[i + 1] = response.template at<T>(mod(delta.y + i, response.rows), delta.x);
            hNeighbors[i + 1] = response.template at<T>(delta.y, mod(delta.x + i, response.cols));
        }

        subDelta.y += subPixelPeak(vNeighbors);
        subDelta.x += subPixelPeak(hNeighbors);

        return subDelta;
    }

    // http://home.isr.uc.pt/~henriques/circulant/
    template <typename T>
    cv::Mat gaussianShapedLabels2D(T sigma, const cv::Size_<T>& size)
    {
        int width = static_cast<int>(size.width);
        int height = static_cast<int>(size.height);

        cv::Mat_<T> rs(height, width);

        CV_Assert(rs.isContinuous());

        T lowerBoundX = static_cast<T>(-floor(width * 0.5) + 1);
        T lowerBoundY = static_cast<T>(-floor(height * 0.5) + 1);

        T* colValues = new T[width];
        T* rsd = rs.template ptr<T>(0, 0);
        T rowValue = 0;
        T sigmaMult = static_cast<T>(-0.5 / (sigma*sigma));

        for (int i = 0; i < width; ++i)
            colValues[i] = (i + lowerBoundX) * (i + lowerBoundX);

        for (int row = 0; row < height; ++row)
        {
            rowValue = (row + lowerBoundY) * (row + lowerBoundY);

            for (int col = 0; col < width; ++col)
            {
                rsd[row*width + col] = exp((colValues[col] + rowValue) * sigmaMult);
            }
        }

        delete[] colValues;

        return rs;
    }

    // http://home.isr.uc.pt/~henriques/circulant/
    template <typename T>
    cv::Mat gaussianShapedLabelsShifted2D(T sigma, const cv::Size_<T>& size)
    {
        cv::Mat y = gaussianShapedLabels2D(sigma, size);
        cv::Point2f delta(static_cast<float>(1 - floor(size.width * 0.5)),
            static_cast<float>(1 - floor(size.height * 0.5)));

        shift(y, y, delta, cv::BORDER_WRAP);

        CV_Assert(y.at<T>(0, 0) == 1.0);
        return y;
    }

    template <typename BT, typename ET>
    cv::Mat pow(BT base_, const cv::Mat_<ET>& exponent)
    {
        cv::Mat dst = cv::Mat(exponent.rows, exponent.cols, exponent.type());
        int widthChannels = exponent.cols * exponent.channels();
        int height = exponent.rows;

        // http://docs.opencv.org/doc/tutorials/core/how_to_scan_images/how_to_scan_images.html#the-efficient-way
        if (exponent.isContinuous())
        {
            widthChannels *= height;
            height = 1;
        }

        int row = 0, col = 0;
        const ET* exponentd = 0;
        ET* dstd = 0;

        for (row = 0; row < height; ++row)
        {
            exponentd = exponent.template ptr<ET>(row);
            dstd = dst.template ptr<ET>(row);

            for (col = 0; col < widthChannels; ++col)
            {
                dstd[col] = std::pow(base_, exponentd[col]);
            }
        }

        return dst;
    }

    // http://en.wikipedia.org/wiki/Hann_function
    template<typename T>
    cv::Mat hanningWindow(int n)
    {
        CV_Assert(n > 0);
        cv::Mat_<T> w = cv::Mat_<T>(n, 1);

        if (n == 1)
        {
            w.template at<T>(0, 0) = 1;
            return w;
        }

        for (int i = 0; i < n; ++i)
            w.template at<T>(i, 0) = static_cast<T>(0.5 * (1.0 - cos(2.0 * 3.14159265358979323846 * i / (n - 1))));

        return w;
    }

    template <typename T>
    void divideSpectrumsNoCcs(const cv::Mat& numerator, const cv::Mat& denominator, cv::Mat& dst)
    {
        // http://mathworld.wolfram.com/ComplexDivision.html
        // (a,b) / (c,d) = ((ac+bd)/v , (bc-ad)/v)
        // with v = (c^2 + d^2)
        // Performance wise implemented according to
        // http://docs.opencv.org/doc/tutorials/core/how_to_scan_images/how_to_scan_images.html#howtoscanimagesopencv
        // TODO: this is still very slow => vectorize (note that mulSpectrums is not vectorized either...)

        int type = numerator.type();
        int channels = numerator.channels();

        CV_Assert(type == denominator.type()
            && numerator.size() == denominator.size()
            && channels == denominator.channels() && channels == 2);
        CV_Assert(type == CV_32FC1 || type == CV_32FC2 || type == CV_64FC1 || type == CV_64FC2);

        dst = cv::Mat(numerator.rows, numerator.cols, type);
        int widthChannels = numerator.cols * channels;
        int height = numerator.rows;

        if (numerator.isContinuous() && denominator.isContinuous())
        {
            widthChannels *= height;
            height = 1;
        }

        int row = 0, col = 0;
        const T* numd, *denomd;
        T* dstd;
        T a, b, c, d, v;

        for (row = 0; row < height; ++row)
        {
            numd = numerator.ptr<T>(row);
            denomd = denominator.ptr<T>(row);
            dstd = dst.ptr<T>(row);

            for (col = 0; col < widthChannels; col += 2)
            {
                a = numd[col];          // real part
                b = numd[col + 1];      // imag part
                c = denomd[col];       // real part
                d = denomd[col + 1];   // imag part

                v = (c * c) + (d * d);

                dstd[col] = (a * c + b * d) / v;
                dstd[col + 1] = (b * c - a * d) / v;
            }
        }
    }

    // http://home.isr.uc.pt/~henriques/circulant/
    template<typename T>
    bool getSubWindow(const cv::Mat& image, cv::Mat& patch, const cv::Size_<T>& size,
        const cv::Point_<T>& pos, cv::Point_<T>* posInSubWindow = 0)
    {
        int width = static_cast<int>(size.width);
        int height = static_cast<int>(size.height);

        int xs = static_cast<int>(std::floor(pos.x) - std::floor(width / 2.0)) + 1;
        int ys = static_cast<int>(std::floor(pos.y) - std::floor(height / 2.0)) + 1;
        T posInSubWindowX = pos.x - xs;
        T posInSubWindowY = pos.y - ys;

        int diffTopX = -xs;
        int diffTopY = -ys;
        int diffBottomX = image.cols - xs - width;
        int diffBottomY = image.rows - ys - height;

        cv::Rect imageRect(0, 0, image.cols, image.rows);
        cv::Rect subRect(xs, ys, width, height);
        subRect &= imageRect;
        cv::Mat subWindow = image(subRect);

        if (subWindow.cols == 0 || subWindow.rows == 0)
            return false;

        if (diffTopX > 0 || diffTopY > 0
            || diffBottomX < 0 || diffBottomY < 0)
        {
            diffTopX = std::max(0, diffTopX);
            diffTopY = std::max(0, diffTopY);
            diffBottomX = std::min(0, diffBottomX);
            diffBottomY = std::min(0, diffBottomY);

            copyMakeBorder(subWindow, subWindow, diffTopY, -diffBottomY,
                diffTopX, -diffBottomX, cv::BORDER_REPLICATE);

            posInSubWindowX += diffTopX;
            posInSubWindowY += diffTopY;
        }

        // this if can be true if the sub window
        // is completely outside the image
        if (width != subWindow.cols ||
            height != subWindow.rows)
            return false;

        if (posInSubWindow != 0)
        {
            posInSubWindow->x = posInSubWindowX;
            posInSubWindow->y = posInSubWindowY;
        }

        patch = subWindow;

        return true;
    }
}

#endif
<commit_msg>Fix scale estimator patch extraction<commit_after>/*
// License Agreement (3-clause BSD License)
// Copyright (c) 2015, Klaus Haag, all rights reserved.
// Third party copyrights and patents are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * 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 names of the copyright holders nor the names of the 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 copyright holders 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.
*/

#ifndef HELPER_H_
#define HELPER_H_

#include <opencv2/core/core.hpp>

#include "cv_ext.hpp"
#include "mat_consts.hpp"

namespace cf_tracking
{
    void dftCcs(const cv::Mat& input, cv::Mat& out, int flags = 0);
    void dftNoCcs(const cv::Mat& input, cv::Mat& out, int flags = 0);
    int mod(int dividend, int divisor);
    void depResize(const cv::Mat& source, cv::Mat& dst, const cv::Size& dsize);

    template<typename T>
    cv::Size_<T> sizeFloor(cv::Size_<T> size)
    {
        return cv::Size_<T>(floor(size.width), floor(size.height));
    }

    template <typename T>
    cv::Mat numberToRowVector(int n)
    {
        cv::Mat_<T> rowVec(n, 1);

        for (int i = 0; i < n; ++i)
            rowVec.template at<T>(i, 0) = static_cast<T>(i + 1);

        return rowVec;
    }

    template <typename T>
    cv::Mat numberToColVector(int n)
    {
        cv::Mat_<T> colVec(1, n);

        for (int i = 0; i < n; ++i)
            colVec.template at<T>(0, i) = static_cast<T>(i + 1);

        return colVec;
    }

    // http://home.isr.uc.pt/~henriques/circulant/
    template <typename T>
    T subPixelPeak(T* p)
    {
        T delta = mat_consts::constants<T>::c0_5 * (p[2] - p[0]) / (2 * p[1] - p[2] - p[0]);

        if (!std::isfinite(delta))
            return 0;

        return delta;
    }

    // http://home.isr.uc.pt/~henriques/circulant/
    template <typename T>
    cv::Point_<T> subPixelDelta(const cv::Mat& response, const cv::Point2i& delta)
    {
        cv::Point_<T> subDelta(static_cast<float>(delta.x), static_cast<float>(delta.y));
        T vNeighbors[3] = {};
        T hNeighbors[3] = {};

        for (int i = -1; i < 2; ++i)
        {
            vNeighbors[i + 1] = response.template at<T>(mod(delta.y + i, response.rows), delta.x);
            hNeighbors[i + 1] = response.template at<T>(delta.y, mod(delta.x + i, response.cols));
        }

        subDelta.y += subPixelPeak(vNeighbors);
        subDelta.x += subPixelPeak(hNeighbors);

        return subDelta;
    }

    // http://home.isr.uc.pt/~henriques/circulant/
    template <typename T>
    cv::Mat gaussianShapedLabels2D(T sigma, const cv::Size_<T>& size)
    {
        int width = static_cast<int>(size.width);
        int height = static_cast<int>(size.height);

        cv::Mat_<T> rs(height, width);

        CV_Assert(rs.isContinuous());

        T lowerBoundX = static_cast<T>(-floor(width * 0.5) + 1);
        T lowerBoundY = static_cast<T>(-floor(height * 0.5) + 1);

        T* colValues = new T[width];
        T* rsd = rs.template ptr<T>(0, 0);
        T rowValue = 0;
        T sigmaMult = static_cast<T>(-0.5 / (sigma*sigma));

        for (int i = 0; i < width; ++i)
            colValues[i] = (i + lowerBoundX) * (i + lowerBoundX);

        for (int row = 0; row < height; ++row)
        {
            rowValue = (row + lowerBoundY) * (row + lowerBoundY);

            for (int col = 0; col < width; ++col)
            {
                rsd[row*width + col] = exp((colValues[col] + rowValue) * sigmaMult);
            }
        }

        delete[] colValues;

        return rs;
    }

    // http://home.isr.uc.pt/~henriques/circulant/
    template <typename T>
    cv::Mat gaussianShapedLabelsShifted2D(T sigma, const cv::Size_<T>& size)
    {
        cv::Mat y = gaussianShapedLabels2D(sigma, size);
        cv::Point2f delta(static_cast<float>(1 - floor(size.width * 0.5)),
            static_cast<float>(1 - floor(size.height * 0.5)));

        shift(y, y, delta, cv::BORDER_WRAP);

        CV_Assert(y.at<T>(0, 0) == 1.0);
        return y;
    }

    template <typename BT, typename ET>
    cv::Mat pow(BT base_, const cv::Mat_<ET>& exponent)
    {
        cv::Mat dst = cv::Mat(exponent.rows, exponent.cols, exponent.type());
        int widthChannels = exponent.cols * exponent.channels();
        int height = exponent.rows;

        // http://docs.opencv.org/doc/tutorials/core/how_to_scan_images/how_to_scan_images.html#the-efficient-way
        if (exponent.isContinuous())
        {
            widthChannels *= height;
            height = 1;
        }

        int row = 0, col = 0;
        const ET* exponentd = 0;
        ET* dstd = 0;

        for (row = 0; row < height; ++row)
        {
            exponentd = exponent.template ptr<ET>(row);
            dstd = dst.template ptr<ET>(row);

            for (col = 0; col < widthChannels; ++col)
            {
                dstd[col] = std::pow(base_, exponentd[col]);
            }
        }

        return dst;
    }

    // http://en.wikipedia.org/wiki/Hann_function
    template<typename T>
    cv::Mat hanningWindow(int n)
    {
        CV_Assert(n > 0);
        cv::Mat_<T> w = cv::Mat_<T>(n, 1);

        if (n == 1)
        {
            w.template at<T>(0, 0) = 1;
            return w;
        }

        for (int i = 0; i < n; ++i)
            w.template at<T>(i, 0) = static_cast<T>(0.5 * (1.0 - cos(2.0 * 3.14159265358979323846 * i / (n - 1))));

        return w;
    }

    template <typename T>
    void divideSpectrumsNoCcs(const cv::Mat& numerator, const cv::Mat& denominator, cv::Mat& dst)
    {
        // http://mathworld.wolfram.com/ComplexDivision.html
        // (a,b) / (c,d) = ((ac+bd)/v , (bc-ad)/v)
        // with v = (c^2 + d^2)
        // Performance wise implemented according to
        // http://docs.opencv.org/doc/tutorials/core/how_to_scan_images/how_to_scan_images.html#howtoscanimagesopencv
        // TODO: this is still very slow => vectorize (note that mulSpectrums is not vectorized either...)

        int type = numerator.type();
        int channels = numerator.channels();

        CV_Assert(type == denominator.type()
            && numerator.size() == denominator.size()
            && channels == denominator.channels() && channels == 2);
        CV_Assert(type == CV_32FC1 || type == CV_32FC2 || type == CV_64FC1 || type == CV_64FC2);

        dst = cv::Mat(numerator.rows, numerator.cols, type);
        int widthChannels = numerator.cols * channels;
        int height = numerator.rows;

        if (numerator.isContinuous() && denominator.isContinuous())
        {
            widthChannels *= height;
            height = 1;
        }

        int row = 0, col = 0;
        const T* numd, *denomd;
        T* dstd;
        T a, b, c, d, v;

        for (row = 0; row < height; ++row)
        {
            numd = numerator.ptr<T>(row);
            denomd = denominator.ptr<T>(row);
            dstd = dst.ptr<T>(row);

            for (col = 0; col < widthChannels; col += 2)
            {
                a = numd[col];          // real part
                b = numd[col + 1];      // imag part
                c = denomd[col];       // real part
                d = denomd[col + 1];   // imag part

                v = (c * c) + (d * d);

                dstd[col] = (a * c + b * d) / v;
                dstd[col + 1] = (b * c - a * d) / v;
            }
        }
    }

    // http://home.isr.uc.pt/~henriques/circulant/
    template<typename T>
    bool getSubWindow(const cv::Mat& image, cv::Mat& patch, const cv::Size_<T>& size,
        const cv::Point_<T>& pos, cv::Point_<T>* posInSubWindow = 0)
    {
        int width = static_cast<int>(size.width);
        int height = static_cast<int>(size.height);

        int xs = static_cast<int>(std::floor(pos.x) - std::floor(width / 2.0)) + 1;
        int ys = static_cast<int>(std::floor(pos.y) - std::floor(height / 2.0)) + 1;
        T posInSubWindowX = pos.x - xs;
        T posInSubWindowY = pos.y - ys;

        int diffTopX = -xs;
        int diffTopY = -ys;
        int diffBottomX = image.cols - xs - width;
        int diffBottomY = image.rows - ys - height;

        cv::Rect imageRect(0, 0, image.cols, image.rows);
        cv::Rect subRect(xs, ys, width, height);
        subRect &= imageRect;
        cv::Mat subWindow = image(subRect);

        if (subWindow.cols == 0 || subWindow.rows == 0)
            return false;

        if (diffTopX > 0 || diffTopY > 0
            || diffBottomX < 0 || diffBottomY < 0)
        {
            diffTopX = std::max(0, diffTopX);
            diffTopY = std::max(0, diffTopY);
            diffBottomX = std::min(0, diffBottomX);
            diffBottomY = std::min(0, diffBottomY);

            copyMakeBorder(subWindow, subWindow, diffTopY, -diffBottomY,
                diffTopX, -diffBottomX, cv::BORDER_REPLICATE);
        }

        // this if can be true if the sub window
        // is completely outside the image
        if (width != subWindow.cols ||
            height != subWindow.rows)
            return false;

        if (posInSubWindow != 0)
        {
            posInSubWindow->x = posInSubWindowX;
            posInSubWindow->y = posInSubWindowY;
        }

        patch = subWindow;

        return true;
    }
}

#endif
<|endoftext|>


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

#include <algorithm>
#include <cmath>
#include <iostream>

#include "gmock/gmock.h"
#include "gtest/gtest.h"

#include "modules/planning/proto/dp_poly_path_config.pb.h"

#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/log.h"
#include "modules/common/util/file.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/integration_tests/planning_test_base.h"
#include "modules/planning/optimizer/dp_poly_path/dp_road_graph.h"

namespace apollo {
namespace planning {

using common::adapter::AdapterManager;

class DpRoadGraphTest : public PlanningTestBase {
 public:
  void SetInitPoint() {
    init_point_.mutable_path_point()->set_x(pose_.position().x());
    init_point_.mutable_path_point()->set_y(pose_.position().y());
    const auto& velocity = pose_.linear_velocity();
    init_point_.set_v(std::hypot(velocity.x(), velocity.y()));
    const auto& acc = pose_.linear_acceleration();
    init_point_.set_a(std::hypot(acc.x(), acc.y()));
    init_point_.set_relative_time(0.0);
  }

  void SetSpeedDataWithConstVeolocity(const double velocity) {
    // speed point params: s, time, v, a, da
    double t = 0.0;
    const double delta_s = 1.0;
    if (velocity > 0.0) {
      for (double s = 0.0; s < 100.0; s += delta_s) {
        speed_data_.add_speed_point(s, t, velocity, 0.0, 0.0);
        t += delta_s / velocity;
      }
    } else {  // when velocity = 0, stand still
      for (double t = 0.0; t < 10.0; t += 0.1) {
        speed_data_.add_speed_point(0.0, t, 0.0, 0.0, 0.0);
      }
    }
  }

  virtual void SetUp() {
    google::InitGoogleLogging("DpRoadGraphTest");
    PlanningTestBase::SetUp();
    SetInitPoint();
    SetSpeedDataWithConstVeolocity(10.0);
    const auto* frame = planning_.GetFrame();
    ASSERT_TRUE(frame != nullptr);
    reference_line_ = &(frame->reference_line());
  }

 protected:
  const ReferenceLine* reference_line_ = nullptr;
  DecisionData decision_data_;
  common::TrajectoryPoint init_point_;
  SpeedData speed_data_;  // input
  PathData path_data_;    // output
};

TEST_F(DpRoadGraphTest, speed_road_graph) {
  DPRoadGraph road_graph(dp_poly_path_config_, init_point_, speed_data_);
  ASSERT_TRUE(reference_line_ != nullptr);
  bool result =
      road_graph.FindPathTunnel(*reference_line_, &decision_data_, &path_data_);
  EXPECT_TRUE(result);
  EXPECT_EQ(648, path_data_.discretized_path().num_of_points());
  EXPECT_EQ(648, path_data_.frenet_frame_path().number_of_points());
  EXPECT_FLOAT_EQ(70.253212,
                  path_data_.frenet_frame_path().points().back().s());
  EXPECT_FLOAT_EQ(0.0, path_data_.frenet_frame_path().points().back().l());
  // export_path_data(path_data_, "/tmp/path.txt");
}

}  // namespace planning
}  // namespace apollo
<commit_msg>fix dp_road_graph_test.<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include <algorithm>
#include <cmath>
#include <iostream>

#include "gmock/gmock.h"
#include "gtest/gtest.h"

#include "modules/planning/proto/dp_poly_path_config.pb.h"

#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/log.h"
#include "modules/common/util/file.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/integration_tests/planning_test_base.h"
#include "modules/planning/optimizer/dp_poly_path/dp_road_graph.h"

namespace apollo {
namespace planning {

using common::adapter::AdapterManager;

class DpRoadGraphTest : public PlanningTestBase {
 public:
  void SetInitPoint() {
    init_point_.mutable_path_point()->set_x(pose_.position().x());
    init_point_.mutable_path_point()->set_y(pose_.position().y());
    const auto& velocity = pose_.linear_velocity();
    init_point_.set_v(std::hypot(velocity.x(), velocity.y()));
    const auto& acc = pose_.linear_acceleration();
    init_point_.set_a(std::hypot(acc.x(), acc.y()));
    init_point_.set_relative_time(0.0);
  }

  void SetSpeedDataWithConstVeolocity(const double velocity) {
    // speed point params: s, time, v, a, da
    double t = 0.0;
    const double delta_s = 1.0;
    if (velocity > 0.0) {
      for (double s = 0.0; s < 100.0; s += delta_s) {
        speed_data_.add_speed_point(s, t, velocity, 0.0, 0.0);
        t += delta_s / velocity;
      }
    } else {  // when velocity = 0, stand still
      for (double t = 0.0; t < 10.0; t += 0.1) {
        speed_data_.add_speed_point(0.0, t, 0.0, 0.0, 0.0);
      }
    }
  }

  virtual void SetUp() {
    google::InitGoogleLogging("DpRoadGraphTest");
    PlanningTestBase::SetUp();
    SetInitPoint();
    SetSpeedDataWithConstVeolocity(10.0);
    const auto* frame = planning_.GetFrame();
    ASSERT_TRUE(frame != nullptr);
    reference_line_ = &(frame->reference_line());
  }

 protected:
  const ReferenceLine* reference_line_ = nullptr;
  DecisionData decision_data_;
  common::TrajectoryPoint init_point_;
  SpeedData speed_data_;  // input
  PathData path_data_;    // output
};

TEST_F(DpRoadGraphTest, speed_road_graph) {
  DPRoadGraph road_graph(dp_poly_path_config_, init_point_, speed_data_);
  ASSERT_TRUE(reference_line_ != nullptr);
  bool result =
      road_graph.FindPathTunnel(*reference_line_, &decision_data_, &path_data_);
  EXPECT_TRUE(result);
  EXPECT_EQ(648, path_data_.discretized_path().num_of_points());
  EXPECT_EQ(648, path_data_.frenet_frame_path().number_of_points());
  EXPECT_FLOAT_EQ(72.00795,
                  path_data_.frenet_frame_path().points().back().s());
  EXPECT_FLOAT_EQ(0.0, path_data_.frenet_frame_path().points().back().l());
  // export_path_data(path_data_, "/tmp/path.txt");
}

}  // namespace planning
}  // namespace apollo
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#ifndef SOFA_COMPONENT_FORCEFIELD_INTERPOLATIONCONTROLLER_INL
#define SOFA_COMPONENT_FORCEFIELD_INTERPOLATIONCONTROLLER_INL

#include "InterpolationController.h"
#include <sofa/core/behavior/ForceField.inl>
#include <sofa/simulation/common/AnimateBeginEvent.h>
#include <sofa/simulation/common/Simulation.h>

#include <sofa/core/visual/VisualParams.h>

namespace sofa
{

namespace component
{

namespace controller
{

using core::behavior::MechanicalState;
using sofa::defaulttype::Vector3;

template<class DataTypes>
InterpolationController<DataTypes>::InterpolationController()
  : fromModel(initLink("original", "Original mesh"))
  , toModel(initLink("objective", "Objective mesh"))
  //, interpModel(initLink("interpolated", "Objective mesh"))
  , f_alphaMax( initData(&f_alphaMax, float(1.0), "alphaMax", "bound defining the max interpolation between the origina (alpha=0) and the objectiv (alpha=1) meshes"))
  , f_alpha0( initData(&f_alpha0, float(0.0), "alpha0", "alpha value at t=0. (0 < alpha0 < 1)"))
  , f_evolution( initData(&f_evolution, (int)STABLE , "evolution", "O for fixity, 1 for inflation, 2 for deflation"))
  , f_period( initData(&f_period, double(1.0), "period", "time to cover all the interpolation positions between original mesh and alpha*(objective mesh), in seconds "))
  , f_interpValues(initData(&f_interpValues, "interpValues", "values or the interpolation"))
{
}

template<class DataTypes>
void InterpolationController<DataTypes>::bwdInit() {
    if (!fromModel || !toModel ) //|| !interpModel)
    {
        serr << "One or more MechanicalStates are missing";
        return;
    }

    fromXs = fromModel->getX();
    toXs = toModel->getX();

    if (fromXs->size() != toXs->size())
    {
       serr << "<InterpolationController> Different number of nodes between the two meshes (original and objective)";
    }

    if (f_alpha0.getValue()>=0.0 && f_alpha0.getValue()<=f_alphaMax.getValue())
    {
        alpha = f_alpha0.getValue();
    }
    else
    {
        serr << "<InterpolationController> Wrong value for alpha0";
        alpha=0;
    }

    sofa::helper::WriteAccessor< DataVecCoord > interpValues = f_interpValues;
    interpValues.resize(fromXs[0].size());
    interpolation(); //interpXs);

}

template<class DataTypes>
void InterpolationController<DataTypes>::interpolation() { //VecCoord &interpXs) {
    sofa::helper::WriteAccessor< DataVecCoord > interpValues = f_interpValues;
//    interpValues.resize(fromXs[0].size());

    for (size_t ptIter=0; ptIter < fromXs[0].size(); ptIter++)
    {
        for (size_t i=0; i< interpValues[0].size(); i++) //interpXs[0].size(); i++)
        {
            //interpXs[ptIter][i] = (fromXs[0][ptIter][i] + alpha*(toXs[0][ptIter][i] - fromXs[0][ptIter][i]) );
            interpValues[ptIter][i] = (fromXs[0][ptIter][i] + alpha*(toXs[0][ptIter][i] - fromXs[0][ptIter][i]) );
        }
    }
}

template<class DataTypes>
void InterpolationController<DataTypes>::handleEvent(core::objectmodel::Event *event) {
    if (dynamic_cast<sofa::simulation::AnimateBeginEvent *>(event))
    {
        if (f_evolution.getValue() != STABLE)
        {
            //helper::WriteAccessor<Data<VecCoord> > interpXData = *interpModel->write(sofa::core::VecCoordId::position());
            //VecCoord& interpXs = interpXData.wref();

            //dAlpha computation(period,dt)
            dAlpha = 1.0 / (f_period.getValue() / this->getContext()->getDt());

            //alpha computation(evolution,alpha,alphaMax,dAlpha)
            switch (static_cast<Evolution_Type>(f_evolution.getValue()))
            {
            case INFLATING:
                alpha = (alpha <= f_alphaMax.getValue()-dAlpha)? alpha+dAlpha : alpha;
                break;

            case DEFLATING:
                alpha = (alpha >= dAlpha)? alpha-dAlpha : alpha;
                break;

            default:
                break;
            }

            //interpolation computation(alpha)
            interpolation();//interpXs);

            if(alpha<dAlpha || alpha>(f_alphaMax.getValue()-dAlpha))
            {
                f_evolution.setValue(STABLE);
            }
        }
    }
}

template<class DataTypes>
void InterpolationController<DataTypes>::draw(const core::visual::VisualParams* vparams)
{
    if ((!vparams->displayFlags().getShowVisualModels()) || f_evolution.getValue()==STABLE) return;

    sofa::helper::ReadAccessor< DataVecCoord > interpValues = f_interpValues;
    if(interpValues.size() != this->fromXs[0].size()) return;
    //const VecCoord *interpXs = interpModel->getX();

    defaulttype::Vec<4,float> color;
    switch (static_cast<Evolution_Type>(f_evolution.getValue()))
    {
    case INFLATING:
        color = defaulttype::Vec<4,float>(1.0f,0.4f,0.4f,1.0f);
        break;

    case DEFLATING:
        color = defaulttype::Vec<4,float>(0.4f,0.4f,1.0f,1.0f);
        break;

    default:
        break;
    }

    float norm = Vector3(this->toXs[0][0][0] - this->fromXs[0][0][0], this->toXs[0][0][1] - this->fromXs[0][0][1], this->toXs[0][0][2] - this->fromXs[0][0][2]).norm()/10.0;
    for (unsigned ptIter = 0; ptIter < fromXs[0].size(); ptIter += fromXs[0].size()/80)
    {
        Vector3 p1(interpValues[ptIter][0],interpValues[ptIter][1],interpValues[ptIter][2]), p2;
        //Vector3 p1(interpXs[0][ptIter][0],interpXs[0][ptIter][1],interpXs[0][ptIter][2]), p2;

        switch (static_cast<Evolution_Type>(f_evolution.getValue()))
        {
        case INFLATING:
            p2 = Vector3(this->toXs[0][ptIter][0],this->toXs[0][ptIter][1],this->toXs[0][ptIter][2]) ;
            break;

        case DEFLATING:
            p2 = Vector3(this->fromXs[0][ptIter][0],this->fromXs[0][ptIter][1],this->fromXs[0][ptIter][2]);
            break;

        default:
            break;
        }

        vparams->drawTool()->drawArrow(p1,p2, norm, color);
    }
}

} // namespace forcefield

} // namespace component

} // namespace sofa

#endif // SOFA_COMPONENT_FORCEFIELD_INTERPOLATIONCONTROLLER_INL

<commit_msg>r10661/sofa : fixing warnings<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#ifndef SOFA_COMPONENT_FORCEFIELD_INTERPOLATIONCONTROLLER_INL
#define SOFA_COMPONENT_FORCEFIELD_INTERPOLATIONCONTROLLER_INL

#include "InterpolationController.h"
#include <sofa/core/behavior/ForceField.inl>
#include <sofa/simulation/common/AnimateBeginEvent.h>
#include <sofa/simulation/common/Simulation.h>

#include <sofa/core/visual/VisualParams.h>

namespace sofa
{

namespace component
{

namespace controller
{

using core::behavior::MechanicalState;
using sofa::defaulttype::Vector3;

template<class DataTypes>
InterpolationController<DataTypes>::InterpolationController()
  : f_evolution( initData(&f_evolution, (int)STABLE , "evolution", "O for fixity, 1 for inflation, 2 for deflation"))
  , f_period( initData(&f_period, double(1.0), "period", "time to cover all the interpolation positions between original mesh and alpha*(objective mesh), in seconds "))
  , f_alphaMax( initData(&f_alphaMax, float(1.0), "alphaMax", "bound defining the max interpolation between the origina (alpha=0) and the objectiv (alpha=1) meshes"))
  , f_alpha0( initData(&f_alpha0, float(0.0), "alpha0", "alpha value at t=0. (0 < alpha0 < 1)"))
  , f_interpValues(initData(&f_interpValues, "interpValues", "values or the interpolation"))
  , fromModel(initLink("original", "Original mesh"))
  , toModel(initLink("objective", "Objective mesh"))
{
}

template<class DataTypes>
void InterpolationController<DataTypes>::bwdInit() {
    if (!fromModel || !toModel ) //|| !interpModel)
    {
        serr << "One or more MechanicalStates are missing";
        return;
    }

    fromXs = fromModel->getX();
    toXs = toModel->getX();

    if (fromXs->size() != toXs->size())
    {
       serr << "<InterpolationController> Different number of nodes between the two meshes (original and objective)";
    }

    if (f_alpha0.getValue()>=0.0 && f_alpha0.getValue()<=f_alphaMax.getValue())
    {
        alpha = f_alpha0.getValue();
    }
    else
    {
        serr << "<InterpolationController> Wrong value for alpha0";
        alpha=0;
    }

    sofa::helper::WriteAccessor< DataVecCoord > interpValues = f_interpValues;
    interpValues.resize(fromXs[0].size());
    interpolation(); //interpXs);

}

template<class DataTypes>
void InterpolationController<DataTypes>::interpolation() { //VecCoord &interpXs) {
    sofa::helper::WriteAccessor< DataVecCoord > interpValues = f_interpValues;
//    interpValues.resize(fromXs[0].size());

    for (size_t ptIter=0; ptIter < fromXs[0].size(); ptIter++)
    {
        for (size_t i=0; i< interpValues[0].size(); i++) //interpXs[0].size(); i++)
        {
            //interpXs[ptIter][i] = (fromXs[0][ptIter][i] + alpha*(toXs[0][ptIter][i] - fromXs[0][ptIter][i]) );
            interpValues[ptIter][i] = (fromXs[0][ptIter][i] + alpha*(toXs[0][ptIter][i] - fromXs[0][ptIter][i]) );
        }
    }
}

template<class DataTypes>
void InterpolationController<DataTypes>::handleEvent(core::objectmodel::Event *event) {
    if (dynamic_cast<sofa::simulation::AnimateBeginEvent *>(event))
    {
        if (f_evolution.getValue() != STABLE)
        {
            //helper::WriteAccessor<Data<VecCoord> > interpXData = *interpModel->write(sofa::core::VecCoordId::position());
            //VecCoord& interpXs = interpXData.wref();

            //dAlpha computation(period,dt)
            dAlpha = 1.0 / (f_period.getValue() / this->getContext()->getDt());

            //alpha computation(evolution,alpha,alphaMax,dAlpha)
            switch (static_cast<Evolution_Type>(f_evolution.getValue()))
            {
            case INFLATING:
                alpha = (alpha <= f_alphaMax.getValue()-dAlpha)? alpha+dAlpha : alpha;
                break;

            case DEFLATING:
                alpha = (alpha >= dAlpha)? alpha-dAlpha : alpha;
                break;

            default:
                break;
            }

            //interpolation computation(alpha)
            interpolation();//interpXs);

            if(alpha<dAlpha || alpha>(f_alphaMax.getValue()-dAlpha))
            {
                f_evolution.setValue(STABLE);
            }
        }
    }
}

template<class DataTypes>
void InterpolationController<DataTypes>::draw(const core::visual::VisualParams* vparams)
{
    if ((!vparams->displayFlags().getShowVisualModels()) || f_evolution.getValue()==STABLE) return;

    sofa::helper::ReadAccessor< DataVecCoord > interpValues = f_interpValues;
    if(interpValues.size() != this->fromXs[0].size()) return;
    //const VecCoord *interpXs = interpModel->getX();

    defaulttype::Vec<4,float> color;
    switch (static_cast<Evolution_Type>(f_evolution.getValue()))
    {
    case INFLATING:
        color = defaulttype::Vec<4,float>(1.0f,0.4f,0.4f,1.0f);
        break;

    case DEFLATING:
        color = defaulttype::Vec<4,float>(0.4f,0.4f,1.0f,1.0f);
        break;

    default:
        break;
    }

    float norm = Vector3(this->toXs[0][0][0] - this->fromXs[0][0][0], this->toXs[0][0][1] - this->fromXs[0][0][1], this->toXs[0][0][2] - this->fromXs[0][0][2]).norm()/10.0;
    for (unsigned ptIter = 0; ptIter < fromXs[0].size(); ptIter += fromXs[0].size()/80)
    {
        Vector3 p1(interpValues[ptIter][0],interpValues[ptIter][1],interpValues[ptIter][2]), p2;
        //Vector3 p1(interpXs[0][ptIter][0],interpXs[0][ptIter][1],interpXs[0][ptIter][2]), p2;

        switch (static_cast<Evolution_Type>(f_evolution.getValue()))
        {
        case INFLATING:
            p2 = Vector3(this->toXs[0][ptIter][0],this->toXs[0][ptIter][1],this->toXs[0][ptIter][2]) ;
            break;

        case DEFLATING:
            p2 = Vector3(this->fromXs[0][ptIter][0],this->fromXs[0][ptIter][1],this->fromXs[0][ptIter][2]);
            break;

        default:
            break;
        }

        vparams->drawTool()->drawArrow(p1,p2, norm, color);
    }
}

} // namespace forcefield

} // namespace component

} // namespace sofa

#endif // SOFA_COMPONENT_FORCEFIELD_INTERPOLATIONCONTROLLER_INL

<|endoftext|>


<commit_before>/* Copyright (C) 2005, Thorvald Natvig <thorvald@natvig.com>

   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

   - Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
   - Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation
     and/or other materials provided with the distribution.
   - Neither the name of the Mumble Developers 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 FOUNDATION 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.
*/

#include "Message.h"
#include "Connection.h"

Connection::Connection(QObject *p, QTcpSocket *qtsSock) : QObject(p) {
	qtsSocket = qtsSock;
	qtsSocket->setParent(this);
	iPacketLength = -1;
	bDisconnectedEmitted = false;
    connect(qtsSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
    connect(qtsSocket, SIGNAL(readyRead()), this, SLOT(socketRead()));
    connect(qtsSocket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
}

Connection::~Connection() {
}

void Connection::socketRead() {
  int iAvailable;
  while (1) {
    iAvailable = qtsSocket->bytesAvailable();

    if (iPacketLength == -1) {
      if (iAvailable < 2)
        return;

      unsigned char a_ucBuffer[2];

	  qtsSocket->read(reinterpret_cast<char *>(a_ucBuffer), 2);
      iPacketLength = ((a_ucBuffer[0] << 8) & 0xff00) + a_ucBuffer[1];
      iAvailable -= 2;
    }

    if ((iPacketLength != -1) && (iAvailable >= iPacketLength)) {
	  QByteArray qbaBuffer = qtsSocket->read(iPacketLength);
	  emit message(qbaBuffer);
      iPacketLength = -1;
    } else {
      return;
    }
  }
}

void Connection::socketError(QAbstractSocket::SocketError) {
	if (! bDisconnectedEmitted) {
		bDisconnectedEmitted = true;
		emit connectionClosed(qtsSocket->errorString());
	}
	qtsSocket->disconnectFromHost();
}

void Connection::socketDisconnected() {
	if (! bDisconnectedEmitted) {
		bDisconnectedEmitted = true;
		emit connectionClosed(QString());
	}
}

void Connection::sendMessage(Message *mMsg) {
	QByteArray qbaBuffer;

	mMsg->messageToNetwork(qbaBuffer);
	sendMessage(qbaBuffer);
}

void Connection::sendMessage(QByteArray &qbaMsg) {
	unsigned char a_ucBuffer[2];

	if (qtsSocket->state() != QAbstractSocket::ConnectedState)
		return;

	if (qbaMsg.size() > 0xffff) {
		qFatal("Connection: Oversized message (%d bytes)", qbaMsg.size());
	}

	a_ucBuffer[0]=(qbaMsg.size() >> 8) & 0xff;
	a_ucBuffer[1]=(qbaMsg.size() & 0xff);
	qtsSocket->write(reinterpret_cast<const char *>(a_ucBuffer), 2);
	qtsSocket->write(qbaMsg);
}

void Connection::forceFlush() {
	if (qtsSocket->state() != QAbstractSocket::ConnectedState)
		return;

	int nodelay;

	qtsSocket->flush();

	nodelay = 1;
	setsockopt(qtsSocket->socketDescriptor(), IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char *>(&nodelay), sizeof(nodelay));
	nodelay = 0;
	setsockopt(qtsSocket->socketDescriptor(), IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char *>(&nodelay), sizeof(nodelay));
}

void Connection::disconnect() {
	qtsSocket->disconnectFromHost();
}

QHostAddress Connection::peerAddress() const {
	return qtsSocket->peerAddress();
}

quint16 Connection::peerPort() const {
	return qtsSocket->peerPort();
}
<commit_msg>UNIX murmur compile fixes<commit_after>/* Copyright (C) 2005, Thorvald Natvig <thorvald@natvig.com>

   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

   - Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
   - Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation
     and/or other materials provided with the distribution.
   - Neither the name of the Mumble Developers 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 FOUNDATION 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.
*/

#include "Message.h"
#include "Connection.h"

#ifdef Q_OS_UNIX
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#endif

Connection::Connection(QObject *p, QTcpSocket *qtsSock) : QObject(p) {
	qtsSocket = qtsSock;
	qtsSocket->setParent(this);
	iPacketLength = -1;
	bDisconnectedEmitted = false;
    connect(qtsSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
    connect(qtsSocket, SIGNAL(readyRead()), this, SLOT(socketRead()));
    connect(qtsSocket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
}

Connection::~Connection() {
}

void Connection::socketRead() {
  int iAvailable;
  while (1) {
    iAvailable = qtsSocket->bytesAvailable();

    if (iPacketLength == -1) {
      if (iAvailable < 2)
        return;

      unsigned char a_ucBuffer[2];

	  qtsSocket->read(reinterpret_cast<char *>(a_ucBuffer), 2);
      iPacketLength = ((a_ucBuffer[0] << 8) & 0xff00) + a_ucBuffer[1];
      iAvailable -= 2;
    }

    if ((iPacketLength != -1) && (iAvailable >= iPacketLength)) {
	  QByteArray qbaBuffer = qtsSocket->read(iPacketLength);
	  emit message(qbaBuffer);
      iPacketLength = -1;
    } else {
      return;
    }
  }
}

void Connection::socketError(QAbstractSocket::SocketError) {
	if (! bDisconnectedEmitted) {
		bDisconnectedEmitted = true;
		emit connectionClosed(qtsSocket->errorString());
	}
	qtsSocket->disconnectFromHost();
}

void Connection::socketDisconnected() {
	if (! bDisconnectedEmitted) {
		bDisconnectedEmitted = true;
		emit connectionClosed(QString());
	}
}

void Connection::sendMessage(Message *mMsg) {
	QByteArray qbaBuffer;

	mMsg->messageToNetwork(qbaBuffer);
	sendMessage(qbaBuffer);
}

void Connection::sendMessage(QByteArray &qbaMsg) {
	unsigned char a_ucBuffer[2];

	if (qtsSocket->state() != QAbstractSocket::ConnectedState)
		return;

	if (qbaMsg.size() > 0xffff) {
		qFatal("Connection: Oversized message (%d bytes)", qbaMsg.size());
	}

	a_ucBuffer[0]=(qbaMsg.size() >> 8) & 0xff;
	a_ucBuffer[1]=(qbaMsg.size() & 0xff);
	qtsSocket->write(reinterpret_cast<const char *>(a_ucBuffer), 2);
	qtsSocket->write(qbaMsg);
}

void Connection::forceFlush() {
	if (qtsSocket->state() != QAbstractSocket::ConnectedState)
		return;

	int nodelay;

	qtsSocket->flush();

	nodelay = 1;
	setsockopt(qtsSocket->socketDescriptor(), IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char *>(&nodelay), sizeof(nodelay));
	nodelay = 0;
	setsockopt(qtsSocket->socketDescriptor(), IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char *>(&nodelay), sizeof(nodelay));
}

void Connection::disconnect() {
	qtsSocket->disconnectFromHost();
}

QHostAddress Connection::peerAddress() const {
	return qtsSocket->peerAddress();
}

quint16 Connection::peerPort() const {
	return qtsSocket->peerPort();
}
<|endoftext|>


<commit_before>#include "lutin.h"

using namespace lutinCompiler;

//implementation of the State5 class methods
State5 :: State5(const char* name) : State(name)
{
}

void State5 ::print()
{
	State::print();
}

bool State5 ::transition(Automat &automat, Symbol *s)
{
    switch(*s)
    {
		case ID_TOKEN: automat.shift(s,new State8("Etat 8"));
					   break;
		default		 : errorDiagnostic(s);
    }
    return false;
}

void State5::errorDiagnostic(Symbol *s)
{

}

//implementation of the State8 class methods
State8 :: State8(const char* name) : State(name)
{
}

void State8 ::print()
{
	State::print();
}

bool State8 ::transition(Automat &automat, Symbol *s)
{
    switch(*s)
    {
	case EQ_TOKEN: automat.shift(s,new State9("Etat 9"));
				   break;
		default		 : errorDiagnostic(s);
    }
    return false;
}

void State8::errorDiagnostic(Symbol *s)
{

}

//implementation of the State9 class methods
State9 :: State9(const char* name) : State(name)
{
}

void State9 ::print()
{

}

bool State9 ::transition(Automat &automat, Symbol *s)
{
    switch(*s)
    {
		case NUM_TOKEN: automat.shift(s,new State20("Etat 20"));
				       break;
		default		 : errorDiagnostic(s);
    }
    return false;
}

void State9::errorDiagnostic(Symbol *s)
{

}

//implementation of the State20 class methods
State20 :: State20(const char* name) : State(name)
{
}

void State20 ::print()
{

}

bool State20 ::transition(Automat &automat, Symbol *s)
{
    switch(*s)
    {
	case SEM_TOKEN: //automat.reduce(new NoTerminalSymbolConstDec(),0);
				   break;
		case COM_TOKEN: //automat.reduce(new NoTerminalSymbolConstDec(),0);
				   break;
		default		 : errorDiagnostic(s);
    }
    return false;
}

void State20::errorDiagnostic(Symbol *s)
{

}

//implementation of the State21 class methods
State21 :: State21(const char* name) : State(name)
{
}

void State21 ::print()
{

}

bool State21 ::transition(Automat &automat, Symbol *s)
{
    switch(*s)
    {
		case SEM_TOKEN: automat.shift(s,new State22("Etat 22"));
				       break;
		case COM_TOKEN: automat.shift(s,new State49("Etat 49"));
				       break;
		default		 : errorDiagnostic(s);
    }
    return false;
}

void State21::errorDiagnostic(Symbol *s)
{

}

//implementation of the State22 class methods
State22 :: State22(const char* name) : State(name)
{
}

void State22 ::print()
{

}

bool State22 ::transition(Automat &automat, Symbol *s)
{
    switch(*s)
    {
		case VAR_TOKEN: automat.shift(s,new State4("Etat 4"));
				       break;
		case CONST_TOKEN: automat.shift(s,new State5("Etat 5"));
				       break;
		case WRITE_TOKEN: //automat.reduce(new NoTerminalSymbolDec(),0);
				       break;
		case READ_TOKEN: //automat.reduce(new NoTerminalSymbolDec(),0);
				       break;
		case ID_TOKEN: //automat.reduce(new NoTerminalSymbolDec(),0);
				       break;
		case EOF_TOKEN: //automat.reduce(new NoTerminalSymbolDec(),0);
				       break;
		case TOKEN_DEC: automat.shift(s,new State23("Etat 23"));
				       break;
		case TOKEN_VAR: automat.shift(s,new State2("Etat 2"));
				       break;
		case TOKEN_CONST: automat.shift(s,new State3("Etat 3"));
				       break;
		default		 : errorDiagnostic(s);
    }
    return false;
}

void State22::errorDiagnostic(Symbol *s)
{

}

//implementation of the State23 class methods
State23 :: State23(const char* name) : State(name)
{
}

void State23 ::print()
{

}

bool State23 ::transition(Automat &automat, Symbol *s)
{
    switch(*s)
    {
		case WRITE_TOKEN: //automat.reduce(new NoTerminalSymbolConst(),7);
				       break;
		case READ_TOKEN: //automat.reduce(new NoTerminalSymbolConst(),7);
				       break;
		case ID_TOKEN: //automat.reduce(new NoTerminalSymbolConst(),7);
				       break;
		case EOF_TOKEN: //automat.reduce(new NoTerminalSymbolConst(),7);
				       break;
		default		 : errorDiagnostic(s);

    }
    return false;
}

void State23::errorDiagnostic(Symbol *s)
{

}

//implementation of the State24 class methods
State24 :: State24(const char* name) : State(name)
{
}

void State24 ::print()
{

}

bool State24 ::transition(Automat &automat, Symbol *s)
{
    switch(*s)
    {
		case EQ_TOKEN: automat.shift(s,new State25("Etat 25"));
				   break;
		default		 : errorDiagnostic(s);
    }
    return false;
}

void State24::errorDiagnostic(Symbol *s)
{

}

//implementation of the State25 class methods
State25 :: State25(const char* name) : State(name)
{
}

void State25 ::print()
{

}

bool State25 ::transition(Automat &automat, Symbol *s)
{
    switch(*s)
    {
		case NUM_TOKEN: automat.shift(s,new State26("Etat 26"));
					   break;
		default		 : errorDiagnostic(s);
    }
    return false;
}

void State25::errorDiagnostic(Symbol *s)
{

}

//implementation of the State26 class methods
State26 :: State26(const char* name) : State(name)
{
}

void State26 ::print()
{

}

bool State26 ::transition(Automat &automat, Symbol *s)
{
    switch(*s)
    {
		case COM_TOKEN: //automat.reduce(new NoTerminalSymbolConstDec(),5);
					   break;
		case SEM_TOKEN: //automat.reduce(new NoTerminalSymbolConstDec(),5);
					   break;
		default		 : errorDiagnostic(s);
    }
    return false;
}

void State26::errorDiagnostic(Symbol *s)
{

}
//implementation of the State26 class methods
State49 :: State49(const char* name) : State(name)
{
}

void State49 ::print()
{

}

bool State49 ::transition(Automat &automat, Symbol *s)
{
    switch(*s)
    {
		case SEM_TOKEN: automat.shift(s,new State24("Etat24"));
					   break;
		default		 : errorDiagnostic(s);
    }
    return false;
}

void State49::errorDiagnostic(Symbol *s)
{

}<commit_msg>Modification on ConstCPP<commit_after>#include "lutin.h"

using namespace lutinCompiler;

//implementation of the State5 class methods
State5 :: State5(const char* name) : State(name)
{
}

void State5 ::print()
{
	State::print();
}

bool State5 ::transition(Automat &automat, Symbol *s)
{
    switch(*s)
    {
		case ID_TOKEN: automat.shift(s,new State8("Etat 8"));
					   break;
		default		 : errorDiagnostic(s);
    }
    return false;
}

void State5::errorDiagnostic(Symbol *s)
{

}

//implementation of the State8 class methods
State8 :: State8(const char* name) : State(name)
{
}

void State8 ::print()
{
	State::print();
}

bool State8 ::transition(Automat &automat, Symbol *s)
{
    switch(*s)
    {
	case EQ_TOKEN: automat.shift(s,new State9("Etat 9"));
				   break;
		default		 : errorDiagnostic(s);
    }
    return false;
}

void State8::errorDiagnostic(Symbol *s)
{

}

//implementation of the State9 class methods
State9 :: State9(const char* name) : State(name)
{
}

void State9 ::print()
{
	State::print();
}

bool State9 ::transition(Automat &automat, Symbol *s)
{
    switch(*s)
    {
		case NUM_TOKEN: automat.shift(s,new State20("Etat 20"));
				       break;
		default		 : errorDiagnostic(s);
    }
    return false;
}

void State9::errorDiagnostic(Symbol *s)
{

}

//implementation of the State20 class methods
State20 :: State20(const char* name) : State(name)
{
}

void State20 ::print()
{
	State::print();
}

bool State20 ::transition(Automat &automat, Symbol *s)
{
    switch(*s)
    {
	case SEM_TOKEN: //automat.reduce(new NoTerminalSymbolConstDec(),0);
				   break;
		case COM_TOKEN: //automat.reduce(new NoTerminalSymbolConstDec(),0);
				   break;
		default		 : errorDiagnostic(s);
    }
    return false;
}

void State20::errorDiagnostic(Symbol *s)
{

}

//implementation of the State21 class methods
State21 :: State21(const char* name) : State(name)
{
}

void State21 ::print()
{
	State::print();
}

bool State21 ::transition(Automat &automat, Symbol *s)
{
    switch(*s)
    {
		case SEM_TOKEN: automat.shift(s,new State22("Etat 22"));
				       break;
		case COM_TOKEN: automat.shift(s,new State49("Etat 49"));
				       break;
		default		 : errorDiagnostic(s);
    }
    return false;
}

void State21::errorDiagnostic(Symbol *s)
{

}

//implementation of the State22 class methods
State22 :: State22(const char* name) : State(name)
{
}

void State22 ::print()
{
	State::print();
}

bool State22 ::transition(Automat &automat, Symbol *s)
{
    switch(*s)
    {
		case VAR_TOKEN: automat.shift(s,new State4("Etat 4"));
				       break;
		case CONST_TOKEN: automat.shift(s,new State5("Etat 5"));
				       break;
		case WRITE_TOKEN: //automat.reduce(new NoTerminalSymbolDec(),0);
				       break;
		case READ_TOKEN: //automat.reduce(new NoTerminalSymbolDec(),0);
				       break;
		case ID_TOKEN: //automat.reduce(new NoTerminalSymbolDec(),0);
				       break;
		case EOF_TOKEN: //automat.reduce(new NoTerminalSymbolDec(),0);
				       break;
		case TOKEN_DEC: automat.shift(s,new State23("Etat 23"));
				       break;
		case TOKEN_VAR: automat.shift(s,new State2("Etat 2"));
				       break;
		case TOKEN_CONST: automat.shift(s,new State3("Etat 3"));
				       break;
		default		 : errorDiagnostic(s);
    }
    return false;
}

void State22::errorDiagnostic(Symbol *s)
{

}

//implementation of the State23 class methods
State23 :: State23(const char* name) : State(name)
{
}

void State23 ::print()
{
	State::print();
}

bool State23 ::transition(Automat &automat, Symbol *s)
{
    switch(*s)
    {
		case WRITE_TOKEN: //automat.reduce(new NoTerminalSymbolConst(),7);
				       break;
		case READ_TOKEN: //automat.reduce(new NoTerminalSymbolConst(),7);
				       break;
		case ID_TOKEN: //automat.reduce(new NoTerminalSymbolConst(),7);
				       break;
		case EOF_TOKEN: //automat.reduce(new NoTerminalSymbolConst(),7);
				       break;
		default		 : errorDiagnostic(s);

    }
    return false;
}

void State23::errorDiagnostic(Symbol *s)
{

}

//implementation of the State24 class methods
State24 :: State24(const char* name) : State(name)
{
}

void State24 ::print()
{
	State::print();
}

bool State24 ::transition(Automat &automat, Symbol *s)
{
    switch(*s)
    {
		case EQ_TOKEN: automat.shift(s,new State25("Etat 25"));
				   break;
		default		 : errorDiagnostic(s);
    }
    return false;
}

void State24::errorDiagnostic(Symbol *s)
{

}

//implementation of the State25 class methods
State25 :: State25(const char* name) : State(name)
{
}

void State25 ::print()
{
	State::print();
}

bool State25 ::transition(Automat &automat, Symbol *s)
{
    switch(*s)
    {
		case NUM_TOKEN: automat.shift(s,new State26("Etat 26"));
					   break;
		default		 : errorDiagnostic(s);
    }
    return false;
}

void State25::errorDiagnostic(Symbol *s)
{

}

//implementation of the State26 class methods
State26 :: State26(const char* name) : State(name)
{
}

void State26 ::print()
{
	State::print();
}

bool State26 ::transition(Automat &automat, Symbol *s)
{
    switch(*s)
    {
		case COM_TOKEN: //automat.reduce(new NoTerminalSymbolConstDec(),5);
					   break;
		case SEM_TOKEN: //automat.reduce(new NoTerminalSymbolConstDec(),5);
					   break;
		default		 : errorDiagnostic(s);
    }
    return false;
}

void State26::errorDiagnostic(Symbol *s)
{

}
//implementation of the State26 class methods
State49 :: State49(const char* name) : State(name)
{
}

void State49 ::print()
{
	State::print();
}

bool State49 ::transition(Automat &automat, Symbol *s)
{
    switch(*s)
    {
		case SEM_TOKEN: automat.shift(s,new State24("Etat24"));
					   break;
		default		 : errorDiagnostic(s);
    }
    return false;
}

void State49::errorDiagnostic(Symbol *s)
{

}<|endoftext|>