<commit_before>#ifndef __se3_urdf_hpp__
#define __se3_urdf_hpp__

#include <urdf_model/model.h>
#include <urdf_parser/urdf_parser.h>

#include <iostream>
#include <boost/foreach.hpp>
#include "pinocchio/multibody/model.hpp"

namespace urdf
{
  typedef boost::shared_ptr<ModelInterface> ModelInterfacePtr;
  typedef boost::shared_ptr<const Joint> JointConstPtr;
  typedef boost::shared_ptr<const Link> LinkConstPtr;
  typedef boost::shared_ptr<Link> LinkPtr;
  typedef boost::shared_ptr<const Inertial> InertialConstPtr;
}

namespace se3
{
  namespace urdf
  {
    Inertia convertFromUrdf( const ::urdf::Inertial& Y )
    {
      const ::urdf::Vector3 & p = Y.origin.position;
      const ::urdf::Rotation & q = Y.origin.rotation;

      const Eigen::Vector3d com(p.x,p.y,p.z);
      const Eigen::Matrix3d & R = Eigen::Quaterniond(q.w,q.x,q.y,q.z).matrix();

      Eigen::Matrix3d I; I << Y.ixx,Y.ixy,Y.ixz
			   ,  Y.ixy,Y.iyy,Y.iyz
			   ,  Y.ixz,Y.iyz,Y.izz;
      return Inertia(Y.mass,com,R*I*R.transpose());
    }

    SE3 convertFromUrdf( const ::urdf::Pose & M )
    {
      const ::urdf::Vector3 & p = M.position;
      const ::urdf::Rotation & q = M.rotation;
      return SE3( Eigen::Quaterniond(q.w,q.x,q.y,q.z).matrix(), Eigen::Vector3d(p.x,p.y,p.z));
    }

    enum AxisCartesian { AXIS_X, AXIS_Y, AXIS_Z, AXIS_UNALIGNED };
    AxisCartesian extractCartesianAxis( const ::urdf::Vector3 & axis )
    {
      if( (axis.x==1.0)&&(axis.y==0.0)&&(axis.z==0.0) )
	return AXIS_X;
      else if( (axis.x==0.0)&&(axis.y==1.0)&&(axis.z==0.0) )
	return AXIS_Y;
      else if( (axis.x==0.0)&&(axis.y==0.0)&&(axis.z==1.0) )
	return AXIS_Z;
      else
	return AXIS_UNALIGNED;
    }

    void parseTree( ::urdf::LinkConstPtr link, Model & model, bool freeFlyer, SE3 placementOffset = SE3::Identity() )
    {

      ::urdf::JointConstPtr joint = link->parent_joint;
      SE3 nextPlacementOffset = SE3::Identity(); // OffSet of the next link. In case we encounter a fixed joint, we need to propagate the length of its attached body to next joint.

      // std::cout << " *** " << link->name << "    < attached by joint ";
      // if(joint)
      //   std::cout << "#" << link->parent_joint->name << std::endl;
      // else std::cout << "###ROOT" << std::endl;

      //assert(link->inertial && "The parser cannot accept trivial mass");
      const Inertia & Y = (link->inertial) ?
	convertFromUrdf(*link->inertial)
	: Inertia::Identity();

     // std::cout << "placementOffset: " << placementOffset << std::endl;

      bool visual = (link->visual) ? true : false;

      if(joint!=NULL)
	{
	  assert(link->getParent()!=NULL);

	  Model::Index parent
	    = (link->getParent()->parent_joint==NULL) ?
	    (freeFlyer ? 1 : 0)
	    : model.getBodyId( link->getParent()->parent_joint->name );
	  //std::cout << joint->name << " === " << parent << std::endl;

      const SE3 & jointPlacement = placementOffset*convertFromUrdf(joint->parent_to_joint_origin_transform);

	  //std::cout << "Parent = " << parent << std::endl;
	  //std::cout << "Placement = " << (Matrix4)jointPlacement << std::endl;

	  switch(joint->type)
	    {
	    case ::urdf::Joint::REVOLUTE:
	    case ::urdf::Joint::CONTINUOUS: // Revolute with no joint limits
	      {
	    Eigen::Vector3d jointAxis(Eigen::Vector3d::Zero());
		AxisCartesian axis = extractCartesianAxis(joint->axis);
		switch(axis)
		  {
		  case AXIS_X:
		    model.addBody( parent, JointModelRX(), jointPlacement, Y, joint->name,link->name, visual );
		    break;
		  case AXIS_Y:
		    model.addBody( parent, JointModelRY(), jointPlacement, Y, joint->name,link->name, visual );
		    break;
		  case AXIS_Z:
		    model.addBody( parent, JointModelRZ(), jointPlacement, Y, joint->name,link->name, visual );
		    break;
		  case AXIS_UNALIGNED:
		  	jointAxis= Eigen::Vector3d( joint->axis.x,joint->axis.y,joint->axis.z );
		    jointAxis.normalize();
		    model.addBody( parent, JointModelRevoluteUnaligned(jointAxis),
				   jointPlacement, Y, joint->name,link->name, visual );
		  	break;
		  default:
		    assert( false && "Fatal Error while extracting revolute joint axis");
		    break;
		  }
		break;
	      }
	    case ::urdf::Joint::PRISMATIC:
	      {
	    AxisCartesian axis = extractCartesianAxis(joint->axis);
		switch(axis)
		  {
		  case AXIS_X:
		    model.addBody( parent, JointModelPX(), jointPlacement, Y, joint->name,link->name, visual );
		    break;
		  case AXIS_Y:
		    model.addBody( parent, JointModelPY(), jointPlacement, Y, joint->name,link->name, visual );
		    break;
		  case AXIS_Z:
		    model.addBody( parent, JointModelPZ(), jointPlacement, Y, joint->name,link->name, visual );
		    break;
		  case AXIS_UNALIGNED:
		  	std::cerr << "Bad axis = (" <<joint->axis.x<<","<<joint->axis.y
			      <<","<<joint->axis.z<<")" << std::endl;
		    assert(false && "Only X, Y or Z axis are accepted." );
		  	break;
		  default:
		    assert( false && "Fatal Error while extracting revolute joint axis");
		    break;
		  }
		break;
	      }
	    case ::urdf::Joint::FIXED:
	      {
            // In case of fixed join:
            //		-add the inertia of the link to his parent in the model
            //		-let all the children become children of parent
            //		-inform the parser of the offset to apply
            //		-add fixed body in model to display it in gepetto-viewer

            model.mergeFixedBody(parent, jointPlacement, Y); //Modify the parent inertia in the model
            SE3 ptjot_se3 = convertFromUrdf(link->parent_joint->parent_to_joint_origin_transform);

            //transformation of the current placement offset
            nextPlacementOffset = placementOffset*ptjot_se3;

            //add the fixed Body in the model for the viewer
            model.addFixedBody(parent,nextPlacementOffset,link->name,visual);

			BOOST_FOREACH(::urdf::LinkPtr child_link,link->child_links)
			{
                child_link->setParent(link->getParent() ); 	//skip the fixed generation
			}
			break;
	      }

	    default:
	      {
		std::cerr << "The joint type " << joint->type << " is not supported." << std::endl;
		assert(false && "Only revolute joint are accepted." );
		break;
	      }
	    }
	    }
      else if(freeFlyer)
	{ /* The link is the root of the body. */
	  model.addBody( 0, JointModelFreeFlyer(), SE3::Identity(), Y, "root", link->name, true );
	}

    BOOST_FOREACH(::urdf::LinkConstPtr child,link->child_links)
	{
      parseTree( child,model,freeFlyer,nextPlacementOffset );
	}
    }

    Model buildModel( const std::string & filename, bool freeFlyer = false )
    {
      Model model;

      ::urdf::ModelInterfacePtr urdfTree = ::urdf::parseURDFFile (filename);
      parseTree(urdfTree->getRoot(),model,freeFlyer);
      return model;
    }

  } // namespace urdf
} // namespace se3

#endif // ifndef __se3_urdf_hpp__

<commit_msg>[Marginal] Cosmetic changes in comments<commit_after>#ifndef __se3_urdf_hpp__
#define __se3_urdf_hpp__

#include <urdf_model/model.h>
#include <urdf_parser/urdf_parser.h>

#include <iostream>
#include <boost/foreach.hpp>
#include "pinocchio/multibody/model.hpp"

namespace urdf
{
  typedef boost::shared_ptr<ModelInterface> ModelInterfacePtr;
  typedef boost::shared_ptr<const Joint> JointConstPtr;
  typedef boost::shared_ptr<const Link> LinkConstPtr;
  typedef boost::shared_ptr<Link> LinkPtr;
  typedef boost::shared_ptr<const Inertial> InertialConstPtr;
}

namespace se3
{
  namespace urdf
  {
    Inertia convertFromUrdf( const ::urdf::Inertial& Y )
    {
      const ::urdf::Vector3 & p = Y.origin.position;
      const ::urdf::Rotation & q = Y.origin.rotation;

      const Eigen::Vector3d com(p.x,p.y,p.z);
      const Eigen::Matrix3d & R = Eigen::Quaterniond(q.w,q.x,q.y,q.z).matrix();

      Eigen::Matrix3d I; I << Y.ixx,Y.ixy,Y.ixz
			   ,  Y.ixy,Y.iyy,Y.iyz
			   ,  Y.ixz,Y.iyz,Y.izz;
      return Inertia(Y.mass,com,R*I*R.transpose());
    }

    SE3 convertFromUrdf( const ::urdf::Pose & M )
    {
      const ::urdf::Vector3 & p = M.position;
      const ::urdf::Rotation & q = M.rotation;
      return SE3( Eigen::Quaterniond(q.w,q.x,q.y,q.z).matrix(), Eigen::Vector3d(p.x,p.y,p.z));
    }

    enum AxisCartesian { AXIS_X, AXIS_Y, AXIS_Z, AXIS_UNALIGNED };
    AxisCartesian extractCartesianAxis( const ::urdf::Vector3 & axis )
    {
      if( (axis.x==1.0)&&(axis.y==0.0)&&(axis.z==0.0) )
	return AXIS_X;
      else if( (axis.x==0.0)&&(axis.y==1.0)&&(axis.z==0.0) )
	return AXIS_Y;
      else if( (axis.x==0.0)&&(axis.y==0.0)&&(axis.z==1.0) )
	return AXIS_Z;
      else
	return AXIS_UNALIGNED;
    }

    void parseTree( ::urdf::LinkConstPtr link, Model & model, bool freeFlyer, SE3 placementOffset = SE3::Identity() )
    {

      ::urdf::JointConstPtr joint = link->parent_joint;
      SE3 nextPlacementOffset = SE3::Identity(); // OffSet of the next link. In case we encounter a fixed joint, we need to propagate the length of its attached body to next joint.

      // std::cout << " *** " << link->name << "    < attached by joint ";
      // if(joint)
      //   std::cout << "#" << link->parent_joint->name << std::endl;
      // else std::cout << "###ROOT" << std::endl;

      //assert(link->inertial && "The parser cannot accept trivial mass");
      const Inertia & Y = (link->inertial) ?
	convertFromUrdf(*link->inertial)
	: Inertia::Identity();

     // std::cout << "placementOffset: " << placementOffset << std::endl;

      bool visual = (link->visual) ? true : false;

      if(joint!=NULL)
	{
	  assert(link->getParent()!=NULL);

	  Model::Index parent
	    = (link->getParent()->parent_joint==NULL) ?
	    (freeFlyer ? 1 : 0)
	    : model.getBodyId( link->getParent()->parent_joint->name );
	  //std::cout << joint->name << " === " << parent << std::endl;

      const SE3 & jointPlacement = placementOffset*convertFromUrdf(joint->parent_to_joint_origin_transform);

	  //std::cout << "Parent = " << parent << std::endl;
	  //std::cout << "Placement = " << (Matrix4)jointPlacement << std::endl;

	  switch(joint->type)
	    {
	    case ::urdf::Joint::REVOLUTE:
	    case ::urdf::Joint::CONTINUOUS: // Revolute with no joint limits
	      {
	    Eigen::Vector3d jointAxis(Eigen::Vector3d::Zero());
		AxisCartesian axis = extractCartesianAxis(joint->axis);
		switch(axis)
		  {
		  case AXIS_X:
		    model.addBody( parent, JointModelRX(), jointPlacement, Y, joint->name,link->name, visual );
		    break;
		  case AXIS_Y:
		    model.addBody( parent, JointModelRY(), jointPlacement, Y, joint->name,link->name, visual );
		    break;
		  case AXIS_Z:
		    model.addBody( parent, JointModelRZ(), jointPlacement, Y, joint->name,link->name, visual );
		    break;
		  case AXIS_UNALIGNED:
		  	jointAxis= Eigen::Vector3d( joint->axis.x,joint->axis.y,joint->axis.z );
		    jointAxis.normalize();
		    model.addBody( parent, JointModelRevoluteUnaligned(jointAxis),
				   jointPlacement, Y, joint->name,link->name, visual );
		  	break;
		  default:
		    assert( false && "Fatal Error while extracting revolute joint axis");
		    break;
		  }
		break;
	      }
	    case ::urdf::Joint::PRISMATIC:
	      {
	    AxisCartesian axis = extractCartesianAxis(joint->axis);
		switch(axis)
		  {
		  case AXIS_X:
		    model.addBody( parent, JointModelPX(), jointPlacement, Y, joint->name,link->name, visual );
		    break;
		  case AXIS_Y:
		    model.addBody( parent, JointModelPY(), jointPlacement, Y, joint->name,link->name, visual );
		    break;
		  case AXIS_Z:
		    model.addBody( parent, JointModelPZ(), jointPlacement, Y, joint->name,link->name, visual );
		    break;
		  case AXIS_UNALIGNED:
		  	std::cerr << "Bad axis = (" <<joint->axis.x<<","<<joint->axis.y
			      <<","<<joint->axis.z<<")" << std::endl;
		    assert(false && "Only X, Y or Z axis are accepted." );
		  	break;
		  default:
		    assert( false && "Fatal Error while extracting prismatic joint axis");
		    break;
		  }
		break;
	      }
	    case ::urdf::Joint::FIXED:
	      {
            // In case of fixed join:
            //		-add the inertia of the link to his parent in the model
            //		-let all the children become children of parent
            //		-inform the parser of the offset to apply
            //		-add fixed body in model to display it in gepetto-viewer

            model.mergeFixedBody(parent, jointPlacement, Y); //Modify the parent inertia in the model
            SE3 ptjot_se3 = convertFromUrdf(link->parent_joint->parent_to_joint_origin_transform);

            //transformation of the current placement offset
            nextPlacementOffset = placementOffset*ptjot_se3;

            //add the fixed Body in the model for the viewer
            model.addFixedBody(parent,nextPlacementOffset,link->name,visual);

			BOOST_FOREACH(::urdf::LinkPtr child_link,link->child_links)
			{
                child_link->setParent(link->getParent() ); 	//skip the fixed generation
			}
			break;
	      }

	    default:
	      {
		std::cerr << "The joint type " << joint->type << " is not supported." << std::endl;
		assert(false && "Only revolute, prismatic and fixed joints are accepted." );
		break;
	      }
	    }
	    }
      else if(freeFlyer)
	{ // The link is the root of the body.
	  model.addBody( 0, JointModelFreeFlyer(), SE3::Identity(), Y, "root", link->name, true );
	}

    BOOST_FOREACH(::urdf::LinkConstPtr child,link->child_links)
	{
      parseTree( child,model,freeFlyer,nextPlacementOffset );
	}
    }

    Model buildModel( const std::string & filename, bool freeFlyer = false )
    {
      Model model;

      ::urdf::ModelInterfacePtr urdfTree = ::urdf::parseURDFFile (filename);
      parseTree(urdfTree->getRoot(),model,freeFlyer);
      return model;
    }

  } // namespace urdf
} // namespace se3

#endif // ifndef __se3_urdf_hpp__

<|endoftext|>


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

#include "chrome/common/ipc_logging.h"

#include "base/command_line.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "base/time.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/ipc_sync_message.h"
#include "chrome/common/ipc_message_utils.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/plugin_messages.h"

#ifdef IPC_MESSAGE_LOG_ENABLED

using base::Time;

// IPC::Logging is allocated as a singleton, so we don't need any kind of
// special retention program.
template <>
struct RunnableMethodTraits<IPC::Logging> {
  static void RetainCallee(IPC::Logging*) {}
  static void ReleaseCallee(IPC::Logging*) {}
};

namespace IPC {

const wchar_t kLoggingEventName[] = L"ChromeIPCLog.%d";
const int kLogSendDelayMs = 100;

Logging::Logging()
    : logging_event_on_(NULL),
      logging_event_off_(NULL),
      enabled_(false),
      sender_(NULL),
      consumer_(NULL),
      queue_invoke_later_pending_(false),
      main_thread_(MessageLoop::current()) {
  memset(log_function_mapping_, sizeof(log_function_mapping_), 0);

  // Create an event for this browser instance that's set when logging is
  // enabled, so child processes can know when logging is enabled.
  int browser_pid;

  const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
  std::wstring process_type =
    parsed_command_line.GetSwitchValue(switches::kProcessType);
  if (process_type.empty()) {
    browser_pid = GetCurrentProcessId();
  } else {
    std::wstring channel_name =
        parsed_command_line.GetSwitchValue(switches::kProcessChannelID);

    browser_pid = _wtoi(channel_name.c_str());
    DCHECK(browser_pid != 0);
  }

  std::wstring event_name = GetEventName(browser_pid, true);
  logging_event_on_ = CreateEvent(NULL, TRUE, FALSE, event_name.c_str());

  event_name = GetEventName(browser_pid, false);
  logging_event_off_ = CreateEvent(NULL, TRUE, FALSE, event_name.c_str());

  RegisterWaitForEvent(true);
}

Logging::~Logging() {
  watcher_.StopWatching();
  CloseHandle(logging_event_on_);
  CloseHandle(logging_event_off_);
}

Logging* Logging::current() {
  return Singleton<Logging>::get();
}

void Logging::RegisterWaitForEvent(bool enabled) {
  watcher_.StopWatching();
  watcher_.StartWatching(
      enabled ? logging_event_on_ : logging_event_off_, this);
}

void Logging::OnObjectSignaled(HANDLE object) {
  enabled_ = object == logging_event_on_;
  RegisterWaitForEvent(!enabled_);
}

void Logging::RegisterMessageLogger(int msg_start, LogFunction* func) {
  int msg_class = msg_start >> 12;
  if (msg_class > arraysize(log_function_mapping_)) {
    NOTREACHED();
    return;
  }

  log_function_mapping_[msg_class] = func;
}

std::wstring Logging::GetEventName(bool enabled) {
  return current()->GetEventName(GetCurrentProcessId(), enabled);
}

std::wstring Logging::GetEventName(int browser_pid, bool enabled) {
  std::wstring result = StringPrintf(kLoggingEventName, browser_pid);
  result += enabled ? L"on" : L"off";
  return result;
}

void Logging::SetConsumer(Consumer* consumer) {
  consumer_ = consumer;
}

void Logging::Enable() {
  ResetEvent(logging_event_off_);
  SetEvent(logging_event_on_);
}

void Logging::Disable() {
  ResetEvent(logging_event_on_);
  SetEvent(logging_event_off_);
}

inline bool Logging::Enabled() const {
  return enabled_;
}

void Logging::OnSendLogs() {
  queue_invoke_later_pending_ = false;
  if (!sender_)
    return;

  Message* msg = new Message(
      MSG_ROUTING_CONTROL, IPC_LOGGING_ID, Message::PRIORITY_NORMAL);
  WriteParam(msg, queued_logs_);
  queued_logs_.clear();
  sender_->Send(msg);
}

void Logging::SetIPCSender(IPC::Message::Sender* sender) {
  sender_ = sender;
}

void Logging::OnReceivedLoggingMessage(const Message& message) {
  std::vector<LogData> data;
  void* iter = NULL;
  if (!ReadParam(&message, &iter, &data))
    return;

  for (size_t i = 0; i < data.size(); ++i) {
    Log(data[i]);
  }
}

void Logging::OnSendMessage(Message* message, const std::wstring& channel_id) {
  if (!Enabled())
    return;

  if (message->is_reply()) {
    LogData* data = message->sync_log_data();
    if (!data)
      return;

    // This is actually the delayed reply to a sync message.  Create a string
    // of the output parameters, add it to the LogData that was earlier stashed
    // with the reply, and log the result.
    data->channel = channel_id;
    GenerateLogData(L"", *message, data);
    Log(*data);
    delete data;
    message->set_sync_log_data(NULL);
  } else {
    // If the time has already been set (i.e. by ChannelProxy), keep that time
    // instead as it's more accurate.
    if (!message->sent_time())
      message->set_sent_time(Time::Now().ToInternalValue());
  }
}

void Logging::OnPreDispatchMessage(const Message& message) {
  message.set_received_time(Time::Now().ToInternalValue());
}

void Logging::OnPostDispatchMessage(const Message& message,
                                    const std::wstring& channel_id) {
  if (!Enabled() || !message.sent_time() || message.dont_log())
    return;

  LogData data;
  GenerateLogData(channel_id, message, &data);

  if (MessageLoop::current() == main_thread_) {
    Log(data);
  } else {
    main_thread_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &Logging::Log, data));
  }
}

void Logging::GetMessageText(uint16 type, std::wstring* name,
                             const Message* message,
                             std::wstring* params) {
  int message_class = type >> 12;
  if (current()->log_function_mapping_[message_class] != NULL) {
    current()->log_function_mapping_[message_class](type, name, message, params);
  } else {
    DLOG(INFO) << "No logger function associated with message class " <<
        message_class;
  }
}

void Logging::Log(const LogData& data) {
  if (consumer_) {
    // We're in the browser process.
    consumer_->Log(data);
  } else {
    // We're in the renderer or plugin processes.
    if (sender_) {
      queued_logs_.push_back(data);
      if (!queue_invoke_later_pending_) {
        queue_invoke_later_pending_ = true;
        MessageLoop::current()->PostDelayedTask(FROM_HERE, NewRunnableMethod(
            this, &Logging::OnSendLogs), kLogSendDelayMs);
      }
    }
  }
}

void GenerateLogData(const std::wstring& channel, const Message& message,
                     LogData* data) {
  if (message.is_reply()) {
    // "data" should already be filled in.
    std::wstring params;
    Logging::GetMessageText(data->type, NULL, &message, &params);

    if (!data->params.empty() && !params.empty())
      data->params += L", ";

    data->flags += L" DR";

    data->params += params;
  } else {
    std::wstring flags;
    if (message.is_sync())
      flags = L"S";

    if (message.is_reply())
      flags += L"R";

    if (message.is_reply_error())
      flags += L"E";

    std::wstring params;
    Logging::GetMessageText(message.type(), NULL, &message, &params);

    data->channel = channel;
    data->type = message.type();
    data->flags = flags;
    data->sent = message.sent_time();
    data->receive = message.received_time();
    data->dispatch = Time::Now().ToInternalValue();
    data->params = params;
  }
}

}

#endif  // IPC_MESSAGE_LOG_ENABLED
<commit_msg>Stop about:ipc crashing<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/ipc_logging.h"

#include "base/command_line.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "base/time.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/ipc_sync_message.h"
#include "chrome/common/ipc_message_utils.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/plugin_messages.h"

#ifdef IPC_MESSAGE_LOG_ENABLED

using base::Time;

// IPC::Logging is allocated as a singleton, so we don't need any kind of
// special retention program.
template <>
struct RunnableMethodTraits<IPC::Logging> {
  static void RetainCallee(IPC::Logging*) {}
  static void ReleaseCallee(IPC::Logging*) {}
};

namespace IPC {

const wchar_t kLoggingEventName[] = L"ChromeIPCLog.%d";
const int kLogSendDelayMs = 100;

Logging::Logging()
    : logging_event_on_(NULL),
      logging_event_off_(NULL),
      enabled_(false),
      sender_(NULL),
      consumer_(NULL),
      queue_invoke_later_pending_(false),
      main_thread_(MessageLoop::current()) {
  memset(log_function_mapping_, 0, sizeof(log_function_mapping_));

  // Create an event for this browser instance that's set when logging is
  // enabled, so child processes can know when logging is enabled.
  int browser_pid;

  const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
  std::wstring process_type =
    parsed_command_line.GetSwitchValue(switches::kProcessType);
  if (process_type.empty()) {
    browser_pid = GetCurrentProcessId();
  } else {
    std::wstring channel_name =
        parsed_command_line.GetSwitchValue(switches::kProcessChannelID);

    browser_pid = _wtoi(channel_name.c_str());
    DCHECK(browser_pid != 0);
  }

  std::wstring event_name = GetEventName(browser_pid, true);
  logging_event_on_ = CreateEvent(NULL, TRUE, FALSE, event_name.c_str());

  event_name = GetEventName(browser_pid, false);
  logging_event_off_ = CreateEvent(NULL, TRUE, FALSE, event_name.c_str());

  RegisterWaitForEvent(true);
}

Logging::~Logging() {
  watcher_.StopWatching();
  CloseHandle(logging_event_on_);
  CloseHandle(logging_event_off_);
}

Logging* Logging::current() {
  return Singleton<Logging>::get();
}

void Logging::RegisterWaitForEvent(bool enabled) {
  watcher_.StopWatching();
  watcher_.StartWatching(
      enabled ? logging_event_on_ : logging_event_off_, this);
}

void Logging::OnObjectSignaled(HANDLE object) {
  enabled_ = object == logging_event_on_;
  RegisterWaitForEvent(!enabled_);
}

void Logging::RegisterMessageLogger(int msg_start, LogFunction* func) {
  int msg_class = msg_start >> 12;
  if (msg_class > arraysize(log_function_mapping_)) {
    NOTREACHED();
    return;
  }

  log_function_mapping_[msg_class] = func;
}

std::wstring Logging::GetEventName(bool enabled) {
  return current()->GetEventName(GetCurrentProcessId(), enabled);
}

std::wstring Logging::GetEventName(int browser_pid, bool enabled) {
  std::wstring result = StringPrintf(kLoggingEventName, browser_pid);
  result += enabled ? L"on" : L"off";
  return result;
}

void Logging::SetConsumer(Consumer* consumer) {
  consumer_ = consumer;
}

void Logging::Enable() {
  ResetEvent(logging_event_off_);
  SetEvent(logging_event_on_);
}

void Logging::Disable() {
  ResetEvent(logging_event_on_);
  SetEvent(logging_event_off_);
}

inline bool Logging::Enabled() const {
  return enabled_;
}

void Logging::OnSendLogs() {
  queue_invoke_later_pending_ = false;
  if (!sender_)
    return;

  Message* msg = new Message(
      MSG_ROUTING_CONTROL, IPC_LOGGING_ID, Message::PRIORITY_NORMAL);
  WriteParam(msg, queued_logs_);
  queued_logs_.clear();
  sender_->Send(msg);
}

void Logging::SetIPCSender(IPC::Message::Sender* sender) {
  sender_ = sender;
}

void Logging::OnReceivedLoggingMessage(const Message& message) {
  std::vector<LogData> data;
  void* iter = NULL;
  if (!ReadParam(&message, &iter, &data))
    return;

  for (size_t i = 0; i < data.size(); ++i) {
    Log(data[i]);
  }
}

void Logging::OnSendMessage(Message* message, const std::wstring& channel_id) {
  if (!Enabled())
    return;

  if (message->is_reply()) {
    LogData* data = message->sync_log_data();
    if (!data)
      return;

    // This is actually the delayed reply to a sync message.  Create a string
    // of the output parameters, add it to the LogData that was earlier stashed
    // with the reply, and log the result.
    data->channel = channel_id;
    GenerateLogData(L"", *message, data);
    Log(*data);
    delete data;
    message->set_sync_log_data(NULL);
  } else {
    // If the time has already been set (i.e. by ChannelProxy), keep that time
    // instead as it's more accurate.
    if (!message->sent_time())
      message->set_sent_time(Time::Now().ToInternalValue());
  }
}

void Logging::OnPreDispatchMessage(const Message& message) {
  message.set_received_time(Time::Now().ToInternalValue());
}

void Logging::OnPostDispatchMessage(const Message& message,
                                    const std::wstring& channel_id) {
  if (!Enabled() || !message.sent_time() || message.dont_log())
    return;

  LogData data;
  GenerateLogData(channel_id, message, &data);

  if (MessageLoop::current() == main_thread_) {
    Log(data);
  } else {
    main_thread_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &Logging::Log, data));
  }
}

void Logging::GetMessageText(uint16 type, std::wstring* name,
                             const Message* message,
                             std::wstring* params) {
  int message_class = type >> 12;
  if (current()->log_function_mapping_[message_class] != NULL) {
    current()->log_function_mapping_[message_class](type, name, message, params);
  } else {
    DLOG(INFO) << "No logger function associated with message class " <<
        message_class;
  }
}

void Logging::Log(const LogData& data) {
  if (consumer_) {
    // We're in the browser process.
    consumer_->Log(data);
  } else {
    // We're in the renderer or plugin processes.
    if (sender_) {
      queued_logs_.push_back(data);
      if (!queue_invoke_later_pending_) {
        queue_invoke_later_pending_ = true;
        MessageLoop::current()->PostDelayedTask(FROM_HERE, NewRunnableMethod(
            this, &Logging::OnSendLogs), kLogSendDelayMs);
      }
    }
  }
}

void GenerateLogData(const std::wstring& channel, const Message& message,
                     LogData* data) {
  if (message.is_reply()) {
    // "data" should already be filled in.
    std::wstring params;
    Logging::GetMessageText(data->type, NULL, &message, &params);

    if (!data->params.empty() && !params.empty())
      data->params += L", ";

    data->flags += L" DR";

    data->params += params;
  } else {
    std::wstring flags;
    if (message.is_sync())
      flags = L"S";

    if (message.is_reply())
      flags += L"R";

    if (message.is_reply_error())
      flags += L"E";

    std::wstring params;
    Logging::GetMessageText(message.type(), NULL, &message, &params);

    data->channel = channel;
    data->type = message.type();
    data->flags = flags;
    data->sent = message.sent_time();
    data->receive = message.received_time();
    data->dispatch = Time::Now().ToInternalValue();
    data->params = params;
  }
}

}

#endif  // IPC_MESSAGE_LOG_ENABLED
<|endoftext|>


<commit_before>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include "ConvImpl.hpp"

#include <boost/assert.hpp>

#include <cmath>
#include <limits>

namespace armnn
{

QuantizedMultiplierSmallerThanOne::QuantizedMultiplierSmallerThanOne(float multiplier)
{
    BOOST_ASSERT(multiplier >= 0.0f && multiplier < 1.0f);
    if (multiplier == 0.0f)
    {
        m_Multiplier = 0;
        m_RightShift = 0;
    }
    else
    {
        const double q = std::frexp(multiplier, &m_RightShift);
        m_RightShift = -m_RightShift;
        int64_t qFixed = static_cast<int64_t>(std::round(q * (1ll << 31)));
        BOOST_ASSERT(qFixed <= (1ll << 31));
        if (qFixed == (1ll << 31))
        {
            qFixed /= 2;
            --m_RightShift;
        }
        BOOST_ASSERT(m_RightShift >= 0);
        BOOST_ASSERT(qFixed <= std::numeric_limits<int32_t>::max());
        m_Multiplier = static_cast<int32_t>(qFixed);
    }
}

int32_t QuantizedMultiplierSmallerThanOne::operator*(int32_t rhs) const
{
    int32_t x = SaturatingRoundingDoublingHighMul(rhs, m_Multiplier);
    return RoundingDivideByPOT(x, m_RightShift);
}

int32_t QuantizedMultiplierSmallerThanOne::SaturatingRoundingDoublingHighMul(int32_t a, int32_t b)
{
    // Check for overflow.
    if (a == b && a == std::numeric_limits<int32_t>::min())
    {
        return std::numeric_limits<int32_t>::max();
    }
    int64_t a_64(a);
    int64_t b_64(b);
    int64_t ab_64 = a_64 * b_64;
    int32_t nudge = ab_64 >= 0 ? (1 << 30) : (1 - (1 << 30));
    int32_t ab_x2_high32 = static_cast<std::int32_t>((ab_64 + nudge) / (1ll << 31));
    return ab_x2_high32;
}

int32_t QuantizedMultiplierSmallerThanOne::RoundingDivideByPOT(int32_t x, int exponent)
{
    BOOST_ASSERT(exponent >= 0 && exponent <= 31);
    int32_t mask = (1 << exponent) - 1;
    int32_t remainder = x & mask;
    int32_t threshold = (mask >> 1) + (x < 0 ? 1 : 0);
    return (x >> exponent) + (remainder > threshold ? 1 : 0);
}

inline unsigned int GetOffset(DataLayout& dataLayout, const TensorShape& shape, unsigned int b, unsigned int c,
                              unsigned int h, unsigned int w)
{
    switch (dataLayout)
    {
        case DataLayout::NHWC:
            b *= shape[1] * shape[2] * shape[3];
            h *= shape[2] * shape[3];
            w *= shape[3];
            break;
        case DataLayout::NCHW:
        default:
            b *= shape[1] * shape[2] * shape[3];
            c *= shape[2] * shape[3];
            h *= shape[3];
            break;
    }
    return b + c + h + w;
}

void Convolve(const TensorShape& rInputShape,
              Decoder<float>& rInputDecoder,
              const TensorShape& rOutputShape,
              Encoder<float>& rOutputEncoder,
              const TensorShape& rFilterShape,
              Decoder<float>& rFilterDecoder,
              bool biasEnabled,
              Decoder<float>* pBiasDecoder,
              DataLayout dataLayout,
              unsigned int paddingTop,
              unsigned int paddingLeft,
              unsigned int xStride,
              unsigned int yStride,
              unsigned int xDilation,
              unsigned int yDilation,
              bool depthwise)
{
    if (biasEnabled && !pBiasDecoder)
    {
        throw InvalidArgumentException("Bias is enabled but the bias data is invalid");
    }
    const armnnUtils::DataLayoutIndexed dataLayoutIndexed(dataLayout);

    const unsigned int channelsIndex = dataLayoutIndexed.GetChannelsIndex();
    const unsigned int heightIndex   = dataLayoutIndexed.GetHeightIndex();
    const unsigned int widthIndex    = dataLayoutIndexed.GetWidthIndex();

    unsigned int depthMultiplier = depthwise ? rFilterShape[0] : 1;
    unsigned int inputChannels   = depthwise ? rFilterShape[1] : rFilterShape[channelsIndex];
    unsigned int outputChannels  = depthwise ? inputChannels * depthMultiplier : rFilterShape[0];

    unsigned int batchSize    = rOutputShape[0];
    unsigned int outputHeight = rOutputShape[heightIndex];
    unsigned int outputWidth  = rOutputShape[widthIndex];
    unsigned int inputHeight  = rInputShape[heightIndex];
    unsigned int inputWidth   = rInputShape[widthIndex];

    unsigned int filterHeight = depthwise ? rFilterShape[2] : rFilterShape[heightIndex];
    unsigned int filterWidth  = depthwise ? rFilterShape[3] : rFilterShape[widthIndex];

    for (unsigned int batchIdx = 0; batchIdx < batchSize; batchIdx++)
    {
        for (unsigned int cOutput = 0; cOutput < outputChannels; cOutput++)
        {
            for (unsigned int yOutput = 0; yOutput < outputHeight; yOutput++)
            {
                for (unsigned int xOutput = 0; xOutput < outputWidth; xOutput++)
                {
                    // This loop goes over each output element.
                    float sum =  0.0f;

                    // For depthwise, each output channel corresponds to exactly one input channel.
                    // For normal, must loop over each input channel.
                    for (unsigned int cInput = 0; cInput < (depthwise ? 1 : inputChannels); cInput++)
                    {
                        unsigned int depthwiseMultiplierIdx = 0;
                        if (depthwise)
                        {
                            cInput = cOutput / depthMultiplier;
                            depthwiseMultiplierIdx = cOutput % depthMultiplier;
                        }

                        for (unsigned int yFilter = 0; yFilter < filterHeight; yFilter++)
                        {
                            for (unsigned int xFilter = 0; xFilter < filterWidth; xFilter++)
                            {
                                // This loop goes over each input element for each output element.
                                unsigned int filterIndex = 0;

                                // Since dimensionality of kernel depends on depthwiseness, so does index.
                                if (depthwise)
                                {
                                    filterIndex = depthwiseMultiplierIdx * filterWidth * filterHeight * inputChannels +
                                                  cInput * filterWidth * filterHeight +
                                                  yFilter * filterWidth +
                                                  xFilter;
                                }
                                else
                                {
                                    if (dataLayout == DataLayout::NHWC)
                                    {
                                        filterIndex = cOutput * filterHeight * filterWidth * inputChannels +
                                                      yFilter * filterWidth * inputChannels +
                                                      xFilter * inputChannels +
                                                      cInput;
                                    }
                                    else
                                    {
                                        filterIndex = cOutput * filterWidth * filterHeight * inputChannels +
                                                      cInput  * filterWidth * filterHeight +
                                                      yFilter * filterWidth +
                                                      xFilter;
                                    }
                                }
                                rFilterDecoder += filterIndex;
                                float filterValue = rFilterDecoder.Get();
                                rFilterDecoder -= filterIndex;

                                unsigned int yInput = yOutput * yStride + yFilter * yDilation;
                                unsigned int xInput = xOutput * xStride + xFilter * xDilation;

                                float inputValue;

                                // Check if we're in the padding.
                                if (yInput < paddingTop || yInput >= inputHeight + paddingTop ||
                                    xInput < paddingLeft || xInput >= inputWidth + paddingLeft )
                                {
                                    inputValue = 0.0f;
                                }
                                else
                                {
                                    unsigned int inputIndex;

                                    if (dataLayout == DataLayout::NHWC)
                                    {
                                        inputIndex = batchIdx * inputHeight * inputWidth  * inputChannels +
                                                     (yInput - paddingTop) * inputWidth * inputChannels +
                                                     (xInput - paddingLeft) * inputChannels +
                                                     cInput;
                                    }
                                    else
                                    {
                                        inputIndex = batchIdx * inputWidth * inputHeight * inputChannels +
                                                     inputWidth * inputHeight * cInput +
                                                     inputWidth * (yInput - paddingTop) +
                                                     xInput - paddingLeft;
                                    }
                                    rInputDecoder += inputIndex;
                                    inputValue = rInputDecoder.Get();
                                    rInputDecoder -= inputIndex;
                                }
                                sum += filterValue * inputValue;
                            }
                        }
                    }

                    if (biasEnabled)
                    {
                        *pBiasDecoder += cOutput;
                        sum += pBiasDecoder->Get();
                        *pBiasDecoder -= cOutput;
                    }
                    unsigned int outIdx = GetOffset(dataLayout, rOutputShape, batchIdx, cOutput, yOutput, xOutput);

                    rOutputEncoder += outIdx;
                    rOutputEncoder.Set(sum);
                    rOutputEncoder -= outIdx;
                }
            }
        }
    }
}

} //namespace armnn
<commit_msg>IVGCVSW-3223 Use GetIndex from DataLayoutIndexed.cpp in ConvImpl.cpp<commit_after>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include "ConvImpl.hpp"

#include <boost/assert.hpp>

#include <cmath>
#include <limits>

namespace armnn
{

QuantizedMultiplierSmallerThanOne::QuantizedMultiplierSmallerThanOne(float multiplier)
{
    BOOST_ASSERT(multiplier >= 0.0f && multiplier < 1.0f);
    if (multiplier == 0.0f)
    {
        m_Multiplier = 0;
        m_RightShift = 0;
    }
    else
    {
        const double q = std::frexp(multiplier, &m_RightShift);
        m_RightShift = -m_RightShift;
        int64_t qFixed = static_cast<int64_t>(std::round(q * (1ll << 31)));
        BOOST_ASSERT(qFixed <= (1ll << 31));
        if (qFixed == (1ll << 31))
        {
            qFixed /= 2;
            --m_RightShift;
        }
        BOOST_ASSERT(m_RightShift >= 0);
        BOOST_ASSERT(qFixed <= std::numeric_limits<int32_t>::max());
        m_Multiplier = static_cast<int32_t>(qFixed);
    }
}

int32_t QuantizedMultiplierSmallerThanOne::operator*(int32_t rhs) const
{
    int32_t x = SaturatingRoundingDoublingHighMul(rhs, m_Multiplier);
    return RoundingDivideByPOT(x, m_RightShift);
}

int32_t QuantizedMultiplierSmallerThanOne::SaturatingRoundingDoublingHighMul(int32_t a, int32_t b)
{
    // Check for overflow.
    if (a == b && a == std::numeric_limits<int32_t>::min())
    {
        return std::numeric_limits<int32_t>::max();
    }
    int64_t a_64(a);
    int64_t b_64(b);
    int64_t ab_64 = a_64 * b_64;
    int32_t nudge = ab_64 >= 0 ? (1 << 30) : (1 - (1 << 30));
    int32_t ab_x2_high32 = static_cast<std::int32_t>((ab_64 + nudge) / (1ll << 31));
    return ab_x2_high32;
}

int32_t QuantizedMultiplierSmallerThanOne::RoundingDivideByPOT(int32_t x, int exponent)
{
    BOOST_ASSERT(exponent >= 0 && exponent <= 31);
    int32_t mask = (1 << exponent) - 1;
    int32_t remainder = x & mask;
    int32_t threshold = (mask >> 1) + (x < 0 ? 1 : 0);
    return (x >> exponent) + (remainder > threshold ? 1 : 0);
}

void Convolve(const TensorShape& rInputShape,
              Decoder<float>& rInputDecoder,
              const TensorShape& rOutputShape,
              Encoder<float>& rOutputEncoder,
              const TensorShape& rFilterShape,
              Decoder<float>& rFilterDecoder,
              bool biasEnabled,
              Decoder<float>* pBiasDecoder,
              DataLayout dataLayout,
              unsigned int paddingTop,
              unsigned int paddingLeft,
              unsigned int xStride,
              unsigned int yStride,
              unsigned int xDilation,
              unsigned int yDilation,
              bool depthwise)
{
    if (biasEnabled && !pBiasDecoder)
    {
        throw InvalidArgumentException("Bias is enabled but the bias data is invalid");
    }
    const armnnUtils::DataLayoutIndexed dataLayoutIndexed(dataLayout);

    const unsigned int channelsIndex = dataLayoutIndexed.GetChannelsIndex();
    const unsigned int heightIndex   = dataLayoutIndexed.GetHeightIndex();
    const unsigned int widthIndex    = dataLayoutIndexed.GetWidthIndex();

    unsigned int depthMultiplier = depthwise ? rFilterShape[0] : 1;
    unsigned int inputChannels   = depthwise ? rFilterShape[1] : rFilterShape[channelsIndex];
    unsigned int outputChannels  = depthwise ? inputChannels * depthMultiplier : rFilterShape[0];

    unsigned int batchSize    = rOutputShape[0];
    unsigned int outputHeight = rOutputShape[heightIndex];
    unsigned int outputWidth  = rOutputShape[widthIndex];
    unsigned int inputHeight  = rInputShape[heightIndex];
    unsigned int inputWidth   = rInputShape[widthIndex];

    unsigned int filterHeight = depthwise ? rFilterShape[2] : rFilterShape[heightIndex];
    unsigned int filterWidth  = depthwise ? rFilterShape[3] : rFilterShape[widthIndex];

    for (unsigned int batchIdx = 0; batchIdx < batchSize; batchIdx++)
    {
        for (unsigned int cOutput = 0; cOutput < outputChannels; cOutput++)
        {
            for (unsigned int yOutput = 0; yOutput < outputHeight; yOutput++)
            {
                for (unsigned int xOutput = 0; xOutput < outputWidth; xOutput++)
                {
                    // This loop goes over each output element.
                    float sum =  0.0f;

                    // For depthwise, each output channel corresponds to exactly one input channel.
                    // For normal, must loop over each input channel.
                    for (unsigned int cInput = 0; cInput < (depthwise ? 1 : inputChannels); cInput++)
                    {
                        unsigned int depthwiseMultiplierIdx = 0;
                        if (depthwise)
                        {
                            cInput = cOutput / depthMultiplier;
                            depthwiseMultiplierIdx = cOutput % depthMultiplier;
                        }

                        for (unsigned int yFilter = 0; yFilter < filterHeight; yFilter++)
                        {
                            for (unsigned int xFilter = 0; xFilter < filterWidth; xFilter++)
                            {
                                // This loop goes over each input element for each output element.
                                unsigned int filterIndex = 0;

                                // Since dimensionality of kernel depends on depthwiseness, so does index.
                                if (depthwise)
                                {
                                    filterIndex = depthwiseMultiplierIdx * filterWidth * filterHeight * inputChannels +
                                                  cInput * filterWidth * filterHeight +
                                                  yFilter * filterWidth +
                                                  xFilter;
                                }
                                else
                                {
                                    filterIndex = dataLayoutIndexed.GetIndex(rFilterShape,
                                                                             cOutput,
                                                                             cInput,
                                                                             yFilter,
                                                                             xFilter);
                                }

                                rFilterDecoder[filterIndex];
                                float filterValue = rFilterDecoder.Get();

                                unsigned int yInput = yOutput * yStride + yFilter * yDilation;
                                unsigned int xInput = xOutput * xStride + xFilter * xDilation;

                                float inputValue;

                                // Check if we're in the padding.
                                if (yInput < paddingTop || yInput >= inputHeight + paddingTop ||
                                    xInput < paddingLeft || xInput >= inputWidth + paddingLeft )
                                {
                                    inputValue = 0.0f;
                                }
                                else
                                {
                                    unsigned int inputIndex = dataLayoutIndexed.GetIndex(rInputShape,
                                                                                batchIdx,
                                                                                cInput,
                                                                                yInput - paddingTop,
                                                                                xInput - paddingLeft);

                                    rInputDecoder[inputIndex];
                                    inputValue = rInputDecoder.Get();
                                }

                                sum += filterValue * inputValue;
                            }
                        }
                    }

                    if (biasEnabled)
                    {
                        (*pBiasDecoder)[cOutput];
                        sum += pBiasDecoder->Get();
                    }

                    unsigned int outIdx = dataLayoutIndexed.GetIndex(rOutputShape, batchIdx, cOutput, yOutput, xOutput);

                    rOutputEncoder[outIdx];
                    rOutputEncoder.Set(sum);
                }
            }
        }
    }
}

} //namespace armnn
<|endoftext|>


<commit_before>// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com>
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

#include <nvcore/StrLib.h>
#include <nvcore/StdStream.h>

#include <nvimage/Image.h>
#include <nvimage/DirectDrawSurface.h>

#include <nvimage/ImageIO.h>

#include "cmdline.h"

#include <time.h> // clock

int main(int argc, char *argv[])
{
	MyAssertHandler assertHandler;
	MyMessageHandler messageHandler;

	bool forcenormal = false;
	bool mipmaps = false;
	bool faces = false;
	bool savePNG = false;

	nv::Path input;
	nv::Path output;

	// Parse arguments.
	for (int i = 1; i < argc; i++)
 	{
		if (strcmp("-forcenormal", argv[i]) == 0)
		{
			forcenormal = true;
		}
		else if (strcmp("-mipmaps", argv[i]) == 0)
		{
			mipmaps = true;
		}
		else if (strcmp("-faces", argv[i]) == 0)
		{
			faces = true;
		}
		else if (strcmp("-format", argv[i]) == 0)
		{
			if (i+1 == argc) break;
			i++;

			if (strcmp("png", argv[i]) == 0) savePNG = true;
			else if (strcmp("tga", argv[i]) == 0) savePNG = false;
			else
			{
				fprintf(stderr, "Unsupported output format '%s', defaulting to 'tga'.\n", argv[i]);
				savePNG = false;
			}
		}
		else if (argv[i][0] != '-')
		{
			input = argv[i];

			if (i+1 < argc && argv[i+1][0] != '-')
			{
				output = argv[i+1];
			}
			else
			{
				output.copy(input.str());
			}

			break;
		}
	}

	printf("NVIDIA Texture Tools - Copyright NVIDIA Corporation 2007\n\n");

	if (input.isNull())
	{
		printf("usage: nvdecompress [options] infile [outfile]\n\n");

		printf("Note: the .tga or .png extension is forced on outfile\n\n");

		printf("Input options:\n");
		printf("  -forcenormal    \tThe input image is a normal map.\n");
		printf("  -mipmaps        \tDecompress all mipmaps.\n");
		printf("  -faces          \tDecompress all faces.\n");
		printf("  -format <format>\tOutput format ('tga' or 'png').\n");

 		return 1;
 	}

	// Load surface.
	nv::DirectDrawSurface dds(input);
	if (!dds.isValid())
	{
		fprintf(stderr, "The file '%s' is not a valid DDS file.\n", input.str());
		return 1;
	}

	if (!dds.isSupported() || dds.isTexture3D())
	{
		fprintf(stderr, "The file '%s' is not a supported DDS file.\n", input.str());
		return 1;
	}

	uint faceCount;
	if (dds.isTexture2D())
	{
		faceCount = 1;
	}
	else
	{
		nvCheck(dds.isTextureCube());
		faceCount = 6;
	}

	uint mipmapCount = dds.mipmapCount();

	clock_t start = clock();

	// apply arguments
	if (forcenormal)
	{
		dds.setNormalFlag(true);
	}
	if (!faces)
	{
		faceCount = 1;
	}
	if (!mipmaps)
	{
		mipmapCount = 1;
	}

	nv::Image mipmap;
	nv::Path name;

	// strip extension, we force the tga extension
	output.stripExtension();

	// extract faces and mipmaps
	for (uint f = 0; f < faceCount; f++)
	{
		for (uint m = 0; m < mipmapCount; m++)
		{
			dds.mipmap(&mipmap, f, m);

			// set output filename, if we are doing faces and/or mipmaps
			name.copy(output);
			if (faces) name.appendFormat("_face%d", f);
			if (mipmaps) name.appendFormat("_mipmap%d", m);
			name.append(savePNG ? ".png" : ".tga");

			nv::StdOutputStream stream(name.str());
			if (stream.isError()) {
				fprintf(stderr, "Error opening '%s' for writting\n", name.str());
				return 1;
			}

			if (savePNG)
				nv::ImageIO::savePNG(stream, &mipmap);
			else
				nv::ImageIO::saveTGA(stream, &mipmap);
		}
	}

	clock_t end = clock();
	printf("\rtime taken: %.3f seconds\n", float(end-start) / CLOCKS_PER_SEC);

	return 0;
}

<commit_msg>Fix build in win64.<commit_after>// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com>
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

#include <nvcore/StrLib.h>
#include <nvcore/StdStream.h>

#include <nvimage/Image.h>
#include <nvimage/DirectDrawSurface.h>

#include <nvimage/ImageIO.h>

#include "cmdline.h"

#include <time.h> // clock

int main(int argc, char *argv[])
{
	MyAssertHandler assertHandler;
	MyMessageHandler messageHandler;

	bool forcenormal = false;
	bool mipmaps = false;
	bool faces = false;
	bool savePNG = false;

	nv::Path input;
	nv::Path output;

	// Parse arguments.
	for (int i = 1; i < argc; i++)
 	{
		if (strcmp("-forcenormal", argv[i]) == 0)
		{
			forcenormal = true;
		}
		else if (strcmp("-mipmaps", argv[i]) == 0)
		{
			mipmaps = true;
		}
		else if (strcmp("-faces", argv[i]) == 0)
		{
			faces = true;
		}
		else if (strcmp("-format", argv[i]) == 0)
		{
			if (i+1 == argc) break;
			i++;

#ifdef HAVE_PNG
			if (strcmp("png", argv[i]) == 0) savePNG = true;
			else
#endif
			if (strcmp("tga", argv[i]) == 0) savePNG = false;
			else
			{
				fprintf(stderr, "Unsupported output format '%s', defaulting to 'tga'.\n", argv[i]);
				savePNG = false;
			}
		}
		else if (argv[i][0] != '-')
		{
			input = argv[i];

			if (i+1 < argc && argv[i+1][0] != '-')
			{
				output = argv[i+1];
			}
			else
			{
				output.copy(input.str());
			}

			break;
		}
	}

	printf("NVIDIA Texture Tools - Copyright NVIDIA Corporation 2007\n\n");

	if (input.isNull())
	{
		printf("usage: nvdecompress [options] infile [outfile]\n\n");

		printf("Note: the .tga or .png extension is forced on outfile\n\n");

		printf("Input options:\n");
		printf("  -forcenormal    \tThe input image is a normal map.\n");
		printf("  -mipmaps        \tDecompress all mipmaps.\n");
		printf("  -faces          \tDecompress all faces.\n");
		printf("  -format <format>\tOutput format ('tga' or 'png').\n");

 		return 1;
 	}

	// Load surface.
	nv::DirectDrawSurface dds(input);
	if (!dds.isValid())
	{
		fprintf(stderr, "The file '%s' is not a valid DDS file.\n", input.str());
		return 1;
	}

	if (!dds.isSupported() || dds.isTexture3D())
	{
		fprintf(stderr, "The file '%s' is not a supported DDS file.\n", input.str());
		return 1;
	}

	uint faceCount;
	if (dds.isTexture2D())
	{
		faceCount = 1;
	}
	else
	{
		nvCheck(dds.isTextureCube());
		faceCount = 6;
	}

	uint mipmapCount = dds.mipmapCount();

	clock_t start = clock();

	// apply arguments
	if (forcenormal)
	{
		dds.setNormalFlag(true);
	}
	if (!faces)
	{
		faceCount = 1;
	}
	if (!mipmaps)
	{
		mipmapCount = 1;
	}

	nv::Image mipmap;
	nv::Path name;

	// strip extension, we force the tga extension
	output.stripExtension();

	// extract faces and mipmaps
	for (uint f = 0; f < faceCount; f++)
	{
		for (uint m = 0; m < mipmapCount; m++)
		{
			dds.mipmap(&mipmap, f, m);

			// set output filename, if we are doing faces and/or mipmaps
			name.copy(output);
			if (faces) name.appendFormat("_face%d", f);
			if (mipmaps) name.appendFormat("_mipmap%d", m);
			name.append(savePNG ? ".png" : ".tga");

			nv::StdOutputStream stream(name.str());
			if (stream.isError()) {
				fprintf(stderr, "Error opening '%s' for writting\n", name.str());
				return 1;
			}

#ifdef HAVE_PNG
			if (savePNG)
			{
				nv::ImageIO::savePNG(stream, &mipmap);
			}
			else
#endif
			{
				nv::ImageIO::saveTGA(stream, &mipmap);
			}
		}
	}

	clock_t end = clock();
	printf("\rtime taken: %.3f seconds\n", float(end-start) / CLOCKS_PER_SEC);

	return 0;
}

<|endoftext|>


<commit_before>#pragma once

#include <string>
#include <vector>

#include <boost/asio.hpp>

namespace elasticsearch {

namespace defaults {

typedef boost::asio::ip::tcp::endpoint endpoint_type;

const endpoint_type endpoint(boost::asio::ip::address_v4(), 9200);

} // namespace defaults

struct settings_t {
    typedef boost::asio::ip::tcp::endpoint endpoint_type;

    std::string index;
    std::vector<endpoint_type> endpoints;

    struct sniffer_t {
        struct {
            bool start;
            bool error;
        } when;

        long timeout;
        long invertal;
    } sniffer;

    int connections;
    int retries;
    long timeout;

    settings_t() :
        index("log"),
        endpoints(std::vector<endpoint_type>({ defaults::endpoint })),
        sniffer({{ true, true }, 10, 60000 }),
        connections(20),
        retries(3),
        timeout(1000)
    {}
};

} // namespace elasticsearch

/*!
  rtm - retries <= max && retries != -1
  srt - sniff retries
  soe - sniff on error

  (1) rq -(rtm !)-> cb(fail).
         -(rtm v)-> succ -> cb(succ).
                 -> fail -(soe v)-> (2)sniff -> succ -> (1)
                                             -> fail -(srt v)-> (2)
                                                     -(srt !)-> cb(fail).
                         -(soe !)-> (1)

  TestCases:
  1. rq -> succ -> cb(succ).
  2. sniff.when.error=false, retries=0:
     rq -> fail -> cb(fail).
  3. sniff.when.error=true, sniff.retries=0, retries=0:
     rq -> fail -> sniff -> fail -> cb(fail).
  4.
  */
<commit_msg>[Code Clean] Cleaning up some comments.<commit_after>#pragma once

#include <string>
#include <vector>

#include <boost/asio.hpp>

namespace elasticsearch {

namespace defaults {

typedef boost::asio::ip::tcp::endpoint endpoint_type;

const endpoint_type endpoint(boost::asio::ip::address_v4(), 9200);

} // namespace defaults

struct settings_t {
    typedef boost::asio::ip::tcp::endpoint endpoint_type;

    std::string index;
    std::vector<endpoint_type> endpoints;

    struct sniffer_t {
        struct {
            bool start;
            bool error;
        } when;

        long timeout;
        long invertal;
    } sniffer;

    int connections;
    int retries;
    long timeout;

    settings_t() :
        index("log"),
        endpoints(std::vector<endpoint_type>({ defaults::endpoint })),
        sniffer({{ true, true }, 10, 60000 }),
        connections(20),
        retries(3),
        timeout(1000)
    {}
};

} // namespace elasticsearch

<|endoftext|>


<commit_before>/*
 * moduleTest.cpp
 *
 *  Created on: 2015年12月15日
 *      Author: nemo
 */

#include "LiveMsgTool/LiveMsgTool.h"
#include "MiTACCSC/MiTACCSC.h"

#include <iostream>

using namespace std;

int main()
{
	MiTACCSC *entryReader = new MiTACCSC();
	MiTACCSC *exitReader = new MiTACCSC();

	LiveMsgTool *liveMsg = new LiveMsgTool();

	cout << "First show" << endl;
	liveMsg->showMsg();

	f fPtr = (f)(&LiveMsgTool::EntryAlive);
	fPtr();

	entryReader->setFunPtr( fPtr );
//	entryReader->setFunPtr( (f)(&LiveMsgTool::EntryAlive) );

	entryReader->runFun();
	exitReader->runFun();

	cout << "\nEnd show" << endl;
	liveMsg->showMsg();

	return 0;
}
<commit_msg>Modified for running non-static member function.<commit_after>/*
 * moduleTest.cpp
 *
 *  Created on: 2015年12月15日
 *      Author: nemo
 */

#include "LiveMsgTool/LiveMsgTool.h"
#include "MiTACCSC/MiTACCSC.h"

#include <iostream>

using namespace std;

int main()
{
	MiTACCSC *entryReader = new MiTACCSC();
	MiTACCSC *exitReader = new MiTACCSC();

	LiveMsgTool *liveMsg = new LiveMsgTool();

	void (LiveMsgTool::*lmsgEntryfun)() = &LiveMsgTool::EntryAlive;
	void (LiveMsgTool::*lmsgExitfun)() = &LiveMsgTool::ExitAlive;

	cout << "First show" << endl;
	liveMsg->showMsg();

	(liveMsg->*lmsgEntryfun)();
	(liveMsg->*lmsgExitfun)();

//	f fPtr = (f)(&LiveMsgTool::EntryAlive);
//	fPtr();

//	entryReader->setFunPtr( fPtr );
//	entryReader->setFunPtr( (f)(&LiveMsgTool::EntryAlive) );

	entryReader->runFun();
	exitReader->runFun();

	cout << "\nEnd show" << endl;
	liveMsg->showMsg();

	return 0;
}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//------------------------------------------------------------------------------

#include "cling/Utils/AST.h"

#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclarationName.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/Lookup.h"

using namespace clang;

namespace cling {
namespace utils {
  Expr* Synthesize::CStyleCastPtrExpr(Sema* S, QualType Ty, uint64_t Ptr) {
    ASTContext& Ctx = S->getASTContext();
    if (!Ty->isPointerType())
      Ty = Ctx.getPointerType(Ty);
    TypeSourceInfo* TSI = Ctx.CreateTypeSourceInfo(Ty);
    const llvm::APInt Addr(8 * sizeof(void *), Ptr);

    Expr* Result = IntegerLiteral::Create(Ctx, Addr, Ctx.UnsignedLongTy,
                                          SourceLocation());
    Result = S->BuildCStyleCastExpr(SourceLocation(), TSI, SourceLocation(),
                                         Result).take();
    assert(Result && "Cannot create CStyleCastPtrExpr");
    return Result;

  }

   static
   NestedNameSpecifier *GetPartiallyDesugaredNNS(const ASTContext& Ctx,
                                                  NestedNameSpecifier *scope,
                                                  const llvm::SmallSet<const Type*, 4>& TypesToSkip){
     // Desugar the scope qualifier if needed.

     const Type *scope_type = scope->getAsType();
     if (scope_type) {
        // this is not a namespace, so we might need to desugar
        NestedNameSpecifier *outer_scope = scope->getPrefix();
        if (outer_scope) {
           outer_scope = GetPartiallyDesugaredNNS(Ctx, outer_scope, TypesToSkip);
        }

        QualType desugared = Transform::GetPartiallyDesugaredType(Ctx,
                                                                  QualType(scope_type,0),
                                                                  TypesToSkip);
        // NOTE: Should check whether the type has changed or not.
        return NestedNameSpecifier::Create(Ctx,outer_scope,false /* template keyword wanted */,
                                           desugared.getTypePtr());
     }
     return scope;
  }

  QualType Transform::GetPartiallyDesugaredType(const ASTContext& Ctx,
                                                QualType QT,
                              const llvm::SmallSet<const Type*, 4>& TypesToSkip){
    // If there are no constains - use the standard desugaring.
    if (!TypesToSkip.size())
      return QT.getDesugaredType(Ctx);

    while(isa<TypedefType>(QT.getTypePtr())) {
      if (!TypesToSkip.count(QT.getTypePtr()))
        QT = QT.getSingleStepDesugaredType(Ctx);
      else
        return QT;
    }
    NestedNameSpecifier *prefix = 0;
    const ElaboratedType *etype = llvm::dyn_cast<ElaboratedType>(QT.getTypePtr());
    if (etype) {
       // We have to also desugar the prefix.

       // Unfortunately this only look at one level, so in
       //   A<type1>::B<type2>::C<type3>::D<type4>
       // A<type1>::B<type2> will be left alone.
       // while C<type3> is desugared by the following code
       // and D<type4> is desugared by the loop below.
       prefix = GetPartiallyDesugaredNNS(Ctx, etype->getQualifier(), TypesToSkip);
       QT = etype->getNamedType();
   }

    // In case of template specializations iterate over the arguments and
    // desugar them as well.
    if(const TemplateSpecializationType* TST
       = dyn_cast<const TemplateSpecializationType>(QT.getTypePtr())) {

      bool mightHaveChanged = false;
      llvm::SmallVector<TemplateArgument, 4> desArgs;
      for(TemplateSpecializationType::iterator I = TST->begin(), E = TST->end();
          I != E; ++I) {
        QualType SubTy = I->getAsType();

        if (SubTy.isNull()) {
           desArgs.push_back(*I);
           continue;
        }

        // Check if the type needs more desugaring and recurse.
        if (isa<TypedefType>(SubTy) || isa<TemplateSpecializationType>(SubTy)) {
          mightHaveChanged = true;
          desArgs.push_back(TemplateArgument(GetPartiallyDesugaredType(Ctx,
                                                                       SubTy,
                                                                  TypesToSkip)));
         } else
            desArgs.push_back(*I);
      }

      // If desugaring happened allocate new type in the AST.
      if (mightHaveChanged) {
        QT = Ctx.getTemplateSpecializationType(TST->getTemplateName(),
                                              desArgs.data(),
                                              desArgs.size(),
                                              TST->getCanonicalTypeInternal());
      }
    }
    if (prefix) {
       QT = Ctx.getElaboratedType(ETK_None,prefix,QT);
    }
    return QT;
  }

  NamespaceDecl* Lookup::Namespace(Sema* S, const char* Name,
                                   DeclContext* Within) {
    DeclarationName DName = &S->Context.Idents.get(Name);
    LookupResult R(*S, DName, SourceLocation(),
                   Sema::LookupNestedNameSpecifierName);
    if (!Within)
      S->LookupName(R, S->TUScope);
    else
      S->LookupQualifiedName(R, Within);

    if (R.empty())
      return 0;

    R.resolveKind();

    return dyn_cast<NamespaceDecl>(R.getFoundDecl());
  }

  NamedDecl* Lookup::Named(Sema* S, const char* Name, DeclContext* Within) {
    DeclarationName DName = &S->Context.Idents.get(Name);

    LookupResult R(*S, DName, SourceLocation(), Sema::LookupOrdinaryName,
                   Sema::ForRedeclaration);
    if (!Within)
      S->LookupName(R, S->TUScope);
    else
      S->LookupQualifiedName(R, Within);

    if (R.empty())
      return 0;

    R.resolveKind();

    return R.getFoundDecl();

  }
} // end namespace utils
} // end namespace cling
<commit_msg>White spaces<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//------------------------------------------------------------------------------

#include "cling/Utils/AST.h"

#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclarationName.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/Lookup.h"

using namespace clang;

namespace cling {
namespace utils {
  Expr* Synthesize::CStyleCastPtrExpr(Sema* S, QualType Ty, uint64_t Ptr) {
    ASTContext& Ctx = S->getASTContext();
    if (!Ty->isPointerType())
      Ty = Ctx.getPointerType(Ty);
    TypeSourceInfo* TSI = Ctx.CreateTypeSourceInfo(Ty);
    const llvm::APInt Addr(8 * sizeof(void *), Ptr);

    Expr* Result = IntegerLiteral::Create(Ctx, Addr, Ctx.UnsignedLongTy,
                                          SourceLocation());
    Result = S->BuildCStyleCastExpr(SourceLocation(), TSI, SourceLocation(),
                                         Result).take();
    assert(Result && "Cannot create CStyleCastPtrExpr");
    return Result;

  }

  static
  NestedNameSpecifier *GetPartiallyDesugaredNNS(const ASTContext& Ctx,
                                                NestedNameSpecifier *scope,
                            const llvm::SmallSet<const Type*, 4>& TypesToSkip){
    // Desugar the scope qualifier if needed.

    const Type *scope_type = scope->getAsType();
    if (scope_type) {
      // this is not a namespace, so we might need to desugar
      NestedNameSpecifier *outer_scope = scope->getPrefix();
      if (outer_scope) {
        outer_scope = GetPartiallyDesugaredNNS(Ctx, outer_scope, TypesToSkip);
      }

      QualType desugared =
        Transform::GetPartiallyDesugaredType(Ctx,
                                             QualType(scope_type,0),
                                             TypesToSkip);
      // NOTE: Should check whether the type has changed or not.
      return NestedNameSpecifier::Create(Ctx,outer_scope,
                                         false /* template keyword wanted */,
                                         desugared.getTypePtr());
    }
    return scope;
  }

  QualType Transform::GetPartiallyDesugaredType(const ASTContext& Ctx,
                                                QualType QT,
                              const llvm::SmallSet<const Type*, 4>& TypesToSkip){
    // If there are no constains - use the standard desugaring.
    if (!TypesToSkip.size())
      return QT.getDesugaredType(Ctx);

    while(isa<TypedefType>(QT.getTypePtr())) {
      if (!TypesToSkip.count(QT.getTypePtr()))
        QT = QT.getSingleStepDesugaredType(Ctx);
      else
        return QT;
    }
    NestedNameSpecifier *prefix = 0;
    const ElaboratedType *etype = llvm::dyn_cast<ElaboratedType>(QT.getTypePtr());
    if (etype) {
      // We have to also desugar the prefix.

      prefix = GetPartiallyDesugaredNNS(Ctx, etype->getQualifier(), TypesToSkip);
      QT = etype->getNamedType();
    }

    // In case of template specializations iterate over the arguments and
    // desugar them as well.
    if(const TemplateSpecializationType* TST
       = dyn_cast<const TemplateSpecializationType>(QT.getTypePtr())) {

      bool mightHaveChanged = false;
      llvm::SmallVector<TemplateArgument, 4> desArgs;
      for(TemplateSpecializationType::iterator I = TST->begin(), E = TST->end();
          I != E; ++I) {
        QualType SubTy = I->getAsType();

        if (SubTy.isNull()) {
           desArgs.push_back(*I);
           continue;
        }

        // Check if the type needs more desugaring and recurse.
        if (isa<TypedefType>(SubTy) || isa<TemplateSpecializationType>(SubTy)) {
          mightHaveChanged = true;
          desArgs.push_back(TemplateArgument(GetPartiallyDesugaredType(Ctx,
                                                                       SubTy,
                                                                  TypesToSkip)));
         } else
            desArgs.push_back(*I);
      }

      // If desugaring happened allocate new type in the AST.
      if (mightHaveChanged) {
        QT = Ctx.getTemplateSpecializationType(TST->getTemplateName(),
                                              desArgs.data(),
                                              desArgs.size(),
                                              TST->getCanonicalTypeInternal());
      }
    }
    if (prefix) {
       QT = Ctx.getElaboratedType(ETK_None,prefix,QT);
    }
    return QT;
  }

  NamespaceDecl* Lookup::Namespace(Sema* S, const char* Name,
                                   DeclContext* Within) {
    DeclarationName DName = &S->Context.Idents.get(Name);
    LookupResult R(*S, DName, SourceLocation(),
                   Sema::LookupNestedNameSpecifierName);
    if (!Within)
      S->LookupName(R, S->TUScope);
    else
      S->LookupQualifiedName(R, Within);

    if (R.empty())
      return 0;

    R.resolveKind();

    return dyn_cast<NamespaceDecl>(R.getFoundDecl());
  }

  NamedDecl* Lookup::Named(Sema* S, const char* Name, DeclContext* Within) {
    DeclarationName DName = &S->Context.Idents.get(Name);

    LookupResult R(*S, DName, SourceLocation(), Sema::LookupOrdinaryName,
                   Sema::ForRedeclaration);
    if (!Within)
      S->LookupName(R, S->TUScope);
    else
      S->LookupQualifiedName(R, Within);

    if (R.empty())
      return 0;

    R.resolveKind();

    return R.getFoundDecl();

  }
} // end namespace utils
} // end namespace cling
<|endoftext|>


<commit_before>/*************************************************************************
 *                                                                       *
 * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith.       *
 * All rights reserved.  Email: russ@q12.org   Web: www.q12.org          *
 *                                                                       *
 * This library is free software; you can redistribute it and/or         *
 * modify it under the terms of EITHER:                                  *
 *   (1) 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. The text of the GNU Lesser      *
 *       General Public License is included with this library in the     *
 *       file LICENSE.TXT.                                               *
 *   (2) The BSD-style license that is included with this library in     *
 *       the file LICENSE-BSD.TXT.                                       *
 *                                                                       *
 * 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 files    *
 * LICENSE.TXT and LICENSE-BSD.TXT for more details.                     *
 *                                                                       *
 *************************************************************************/

/*

TODO
----

* gettimeofday() and the pentium time stamp counter return the real time,
  not the process time. fix this somehow!

*/

#include <ode/common.h>
#include <ode/timer.h>

// misc defines
#define ALLOCA dALLOCA16

//****************************************************************************
// implementation for windows based on the multimedia performance counter.

#ifdef WIN32

#include "windows.h"

static inline void getClockCount (unsigned long cc[2])
{
  LARGE_INTEGER a;
  QueryPerformanceCounter (&a);
  cc[0] = a.LowPart;
  cc[1] = a.HighPart;
}

static inline void serialize()
{
}

static inline double loadClockCount (unsigned long cc[2])
{
  LARGE_INTEGER a;
  a.LowPart = cc[0];
  a.HighPart = cc[1];
  return double(a.QuadPart);
}

double dTimerResolution()
{
  return 1.0/dTimerTicksPerSecond();
}

double dTimerTicksPerSecond()
{
  static int query=0;
  static double hz=0.0;
  if (!query) {
    LARGE_INTEGER a;
    QueryPerformanceFrequency (&a);
    hz = double(a.QuadPart);
    query = 1;
  }
  return hz;
}

#endif

//****************************************************************************
// implementation based on the pentium time stamp counter. the timer functions
// can be serializing or non-serializing. serializing will ensure that all
// instructions have executed and data has been written back before the cpu
// time stamp counter is read. the CPUID instruction is used to serialize.

#if defined(PENTIUM) && !defined(WIN32)

// we need to know the clock rate so that the timing function can report
// accurate times. this number only needs to be set accurately if we're
// doing performance tests and care about real-world time numbers - otherwise,
// just ignore this. i have not worked out how to determine this number
// automatically yet.

#define PENTIUM_HZ (500e6)

static inline void getClockCount (unsigned long cc[2])
{
  asm volatile ("
	rdtsc
	movl %%eax,(%%esi)
	movl %%edx,4(%%esi)"
	: : "S" (cc) : "%eax","%edx","cc","memory");
}

static inline void serialize()
{
  asm volatile ("
	mov $0,%%eax
	cpuid"
	: : : "%eax","%ebx","%ecx","%edx","cc","memory");
}

static inline double loadClockCount (unsigned long a[2])
{
  double ret;
  asm volatile ("fildll %1; fstpl %0" : "=m" (ret) : "m" (a[0]) :
		"cc","memory");
  return ret;
}

double dTimerResolution()
{
  return 1.0/PENTIUM_HZ;
}

double dTimerTicksPerSecond()
{
  return PENTIUM_HZ;
}

#endif

//****************************************************************************
// otherwise, do the implementation based on gettimeofday().

#if !defined(PENTIUM) && !defined(WIN32)

#ifndef macintosh

#include <sys/time.h>
#include <unistd.h>

static inline void getClockCount (unsigned long cc[2])
{
  struct timeval tv;
  gettimeofday (&tv,0);
  cc[0] = tv.tv_usec;
  cc[1] = tv.tv_sec;
}

#else // macintosh

#include <MacTypes.h>
#include <Timer.h>

static inline void getClockCount (unsigned long cc[2])
{
  UnsignedWide ms;
  Microseconds (&ms);
  cc[1] = ms.lo / 1000000;
  cc[0] = ms.lo - ( cc[1] * 1000000 );
}

#endif

static inline void serialize()
{
}

static inline double loadClockCount (unsigned long a[2])
{
  return a[1]*1.0e6 + a[0];
}

double dTimerResolution()
{
  unsigned long cc1[2],cc2[2];
  getClockCount (cc1);
  do {
    getClockCount (cc2);
  }
  while (cc1[0]==cc2[0] && cc1[1]==cc2[1]);
  do {
    getClockCount (cc1);
  }
  while (cc1[0]==cc2[0] && cc1[1]==cc2[1]);
  double t1 = loadClockCount (cc1);
  double t2 = loadClockCount (cc2);
  return (t1-t2) / dTimerTicksPerSecond();
}

double dTimerTicksPerSecond()
{
  return 1000000;
}

#endif

//****************************************************************************
// stop watches

void dStopwatchReset (dStopwatch *s)
{
  s->time = 0;
  s->cc[0] = 0;
  s->cc[1] = 0;
}

void dStopwatchStart (dStopwatch *s)
{
  serialize();
  getClockCount (s->cc);
}

void dStopwatchStop  (dStopwatch *s)
{
  unsigned long cc[2];
  serialize();
  getClockCount (cc);
  double t1 = loadClockCount (s->cc);
  double t2 = loadClockCount (cc);
  s->time += t2-t1;
}

double dStopwatchTime (dStopwatch *s)
{
  return s->time / dTimerTicksPerSecond();
}

//****************************************************************************
// code timers

// maximum number of events to record
#define MAXNUM 100

static int num = 0;		// number of entries used in event array
static struct {
  unsigned long cc[2];		// clock counts
  double total_t;		// total clocks used in this slot.
  double total_p;		// total percentage points used in this slot.
  int count;			// number of times this slot has been updated.
  char *description;		// pointer to static string
} event[MAXNUM];

// make sure all slot totals and counts reset to 0 at start

static void initSlots()
{
  static int initialized=0;
  if (!initialized) {
    for (int i=0; i<MAXNUM; i++) {
      event[i].count = 0;
      event[i].total_t = 0;
      event[i].total_p = 0;
    }
    initialized = 1;
  }
}

void dTimerStart (const char *description)
{
  initSlots();
  event[0].description = const_cast<char*> (description);
  num = 1;
  serialize();
  getClockCount (event[0].cc);
}

void dTimerNow (const char *description)
{
  if (num < MAXNUM) {
    // do not serialize
    getClockCount (event[num].cc);
    event[num].description = const_cast<char*> (description);
    num++;
  }
}

void dTimerEnd()
{
  if (num < MAXNUM) {
    serialize();
    getClockCount (event[num].cc);
    event[num].description = "TOTAL";
    num++;
  }
}

//****************************************************************************
// print report

static void fprintDoubleWithPrefix (FILE *f, double a, char *fmt)
{
  if (a >= 0.999999) {
    fprintf (f,fmt,a);
    return;
  }
  a *= 1000.0;
  if (a >= 0.999999) {
    fprintf (f,fmt,a);
    fprintf (f,"m");
    return;
  }
  a *= 1000.0;
  if (a >= 0.999999) {
    fprintf (f,fmt,a);
    fprintf (f,"u");
    return;
  }
  a *= 1000.0;
  fprintf (f,fmt,a);
  fprintf (f,"n");
}

void dTimerReport (FILE *fout, int average)
{
  int i,maxl;
  double ccunit = 1.0/dTimerTicksPerSecond();
  fprintf (fout,"\nTimer Report (");
  fprintDoubleWithPrefix (fout,ccunit,"%.2f ");
  fprintf (fout,"s resolution)\n------------\n");
  if (num < 1) return;

  // get maximum description length
  maxl = 0;
  for (i=0; i<num; i++) {
    int l = strlen (event[i].description);
    if (l > maxl) maxl = l;
  }

  // calculate total time
  double t1 = loadClockCount (event[0].cc);
  double t2 = loadClockCount (event[num-1].cc);
  double total = t2 - t1;
  if (total <= 0) total = 1;

  // compute time difference for all slots except the last one. update totals
  double *times = (double*) ALLOCA (num * sizeof(double));
  for (i=0; i < (num-1); i++) {
    double t1 = loadClockCount (event[i].cc);
    double t2 = loadClockCount (event[i+1].cc);
    times[i] = t2 - t1;
    event[i].count++;
    event[i].total_t += times[i];
    event[i].total_p += times[i]/total * 100.0;
  }

  // print report (with optional averages)
  for (i=0; i<num; i++) {
    double t,p;
    if (i < (num-1)) {
      t = times[i];
      p = t/total * 100.0;
    }
    else {
      t = total;
      p = 100.0;
    }
    fprintf (fout,"%-*s %7.2fms %6.2f%%",maxl,event[i].description,
	     t*ccunit * 1000.0, p);
    if (average && i < (num-1)) {
      fprintf (fout,"  (avg %7.2fms %6.2f%%)",
	       (event[i].total_t / event[i].count)*ccunit * 1000.0,
	       event[i].total_p / event[i].count);
    }
    fprintf (fout,"\n");
  }
  fprintf (fout,"\n");
}
<commit_msg>multi-line string literals are deprecated<commit_after>/*************************************************************************
 *                                                                       *
 * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith.       *
 * All rights reserved.  Email: russ@q12.org   Web: www.q12.org          *
 *                                                                       *
 * This library is free software; you can redistribute it and/or         *
 * modify it under the terms of EITHER:                                  *
 *   (1) 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. The text of the GNU Lesser      *
 *       General Public License is included with this library in the     *
 *       file LICENSE.TXT.                                               *
 *   (2) The BSD-style license that is included with this library in     *
 *       the file LICENSE-BSD.TXT.                                       *
 *                                                                       *
 * 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 files    *
 * LICENSE.TXT and LICENSE-BSD.TXT for more details.                     *
 *                                                                       *
 *************************************************************************/

/*

TODO
----

* gettimeofday() and the pentium time stamp counter return the real time,
  not the process time. fix this somehow!

*/

#include <ode/common.h>
#include <ode/timer.h>

// misc defines
#define ALLOCA dALLOCA16

//****************************************************************************
// implementation for windows based on the multimedia performance counter.

#ifdef WIN32

#include "windows.h"

static inline void getClockCount (unsigned long cc[2])
{
  LARGE_INTEGER a;
  QueryPerformanceCounter (&a);
  cc[0] = a.LowPart;
  cc[1] = a.HighPart;
}

static inline void serialize()
{
}

static inline double loadClockCount (unsigned long cc[2])
{
  LARGE_INTEGER a;
  a.LowPart = cc[0];
  a.HighPart = cc[1];
  return double(a.QuadPart);
}

double dTimerResolution()
{
  return 1.0/dTimerTicksPerSecond();
}

double dTimerTicksPerSecond()
{
  static int query=0;
  static double hz=0.0;
  if (!query) {
    LARGE_INTEGER a;
    QueryPerformanceFrequency (&a);
    hz = double(a.QuadPart);
    query = 1;
  }
  return hz;
}

#endif

//****************************************************************************
// implementation based on the pentium time stamp counter. the timer functions
// can be serializing or non-serializing. serializing will ensure that all
// instructions have executed and data has been written back before the cpu
// time stamp counter is read. the CPUID instruction is used to serialize.

#if defined(PENTIUM) && !defined(WIN32)

// we need to know the clock rate so that the timing function can report
// accurate times. this number only needs to be set accurately if we're
// doing performance tests and care about real-world time numbers - otherwise,
// just ignore this. i have not worked out how to determine this number
// automatically yet.

#define PENTIUM_HZ (500e6)

static inline void getClockCount (unsigned long cc[2])
{
  asm volatile (
	"rdtsc\n"
	"movl %%eax,(%%esi)\n"
	"movl %%edx,4(%%esi)\n"
	: : "S" (cc) : "%eax","%edx","cc","memory");
}

static inline void serialize()
{
  asm volatile (
	"mov $0,%%eax\n"
	"cpuid\n"
	: : : "%eax","%ebx","%ecx","%edx","cc","memory");
}

static inline double loadClockCount (unsigned long a[2])
{
  double ret;
  asm volatile ("fildll %1; fstpl %0" : "=m" (ret) : "m" (a[0]) :
		"cc","memory");
  return ret;
}

double dTimerResolution()
{
  return 1.0/PENTIUM_HZ;
}

double dTimerTicksPerSecond()
{
  return PENTIUM_HZ;
}

#endif

//****************************************************************************
// otherwise, do the implementation based on gettimeofday().

#if !defined(PENTIUM) && !defined(WIN32)

#ifndef macintosh

#include <sys/time.h>
#include <unistd.h>

static inline void getClockCount (unsigned long cc[2])
{
  struct timeval tv;
  gettimeofday (&tv,0);
  cc[0] = tv.tv_usec;
  cc[1] = tv.tv_sec;
}

#else // macintosh

#include <MacTypes.h>
#include <Timer.h>

static inline void getClockCount (unsigned long cc[2])
{
  UnsignedWide ms;
  Microseconds (&ms);
  cc[1] = ms.lo / 1000000;
  cc[0] = ms.lo - ( cc[1] * 1000000 );
}

#endif

static inline void serialize()
{
}

static inline double loadClockCount (unsigned long a[2])
{
  return a[1]*1.0e6 + a[0];
}

double dTimerResolution()
{
  unsigned long cc1[2],cc2[2];
  getClockCount (cc1);
  do {
    getClockCount (cc2);
  }
  while (cc1[0]==cc2[0] && cc1[1]==cc2[1]);
  do {
    getClockCount (cc1);
  }
  while (cc1[0]==cc2[0] && cc1[1]==cc2[1]);
  double t1 = loadClockCount (cc1);
  double t2 = loadClockCount (cc2);
  return (t1-t2) / dTimerTicksPerSecond();
}

double dTimerTicksPerSecond()
{
  return 1000000;
}

#endif

//****************************************************************************
// stop watches

void dStopwatchReset (dStopwatch *s)
{
  s->time = 0;
  s->cc[0] = 0;
  s->cc[1] = 0;
}

void dStopwatchStart (dStopwatch *s)
{
  serialize();
  getClockCount (s->cc);
}

void dStopwatchStop  (dStopwatch *s)
{
  unsigned long cc[2];
  serialize();
  getClockCount (cc);
  double t1 = loadClockCount (s->cc);
  double t2 = loadClockCount (cc);
  s->time += t2-t1;
}

double dStopwatchTime (dStopwatch *s)
{
  return s->time / dTimerTicksPerSecond();
}

//****************************************************************************
// code timers

// maximum number of events to record
#define MAXNUM 100

static int num = 0;		// number of entries used in event array
static struct {
  unsigned long cc[2];		// clock counts
  double total_t;		// total clocks used in this slot.
  double total_p;		// total percentage points used in this slot.
  int count;			// number of times this slot has been updated.
  char *description;		// pointer to static string
} event[MAXNUM];

// make sure all slot totals and counts reset to 0 at start

static void initSlots()
{
  static int initialized=0;
  if (!initialized) {
    for (int i=0; i<MAXNUM; i++) {
      event[i].count = 0;
      event[i].total_t = 0;
      event[i].total_p = 0;
    }
    initialized = 1;
  }
}

void dTimerStart (const char *description)
{
  initSlots();
  event[0].description = const_cast<char*> (description);
  num = 1;
  serialize();
  getClockCount (event[0].cc);
}

void dTimerNow (const char *description)
{
  if (num < MAXNUM) {
    // do not serialize
    getClockCount (event[num].cc);
    event[num].description = const_cast<char*> (description);
    num++;
  }
}

void dTimerEnd()
{
  if (num < MAXNUM) {
    serialize();
    getClockCount (event[num].cc);
    event[num].description = "TOTAL";
    num++;
  }
}

//****************************************************************************
// print report

static void fprintDoubleWithPrefix (FILE *f, double a, char *fmt)
{
  if (a >= 0.999999) {
    fprintf (f,fmt,a);
    return;
  }
  a *= 1000.0;
  if (a >= 0.999999) {
    fprintf (f,fmt,a);
    fprintf (f,"m");
    return;
  }
  a *= 1000.0;
  if (a >= 0.999999) {
    fprintf (f,fmt,a);
    fprintf (f,"u");
    return;
  }
  a *= 1000.0;
  fprintf (f,fmt,a);
  fprintf (f,"n");
}

void dTimerReport (FILE *fout, int average)
{
  int i,maxl;
  double ccunit = 1.0/dTimerTicksPerSecond();
  fprintf (fout,"\nTimer Report (");
  fprintDoubleWithPrefix (fout,ccunit,"%.2f ");
  fprintf (fout,"s resolution)\n------------\n");
  if (num < 1) return;

  // get maximum description length
  maxl = 0;
  for (i=0; i<num; i++) {
    int l = strlen (event[i].description);
    if (l > maxl) maxl = l;
  }

  // calculate total time
  double t1 = loadClockCount (event[0].cc);
  double t2 = loadClockCount (event[num-1].cc);
  double total = t2 - t1;
  if (total <= 0) total = 1;

  // compute time difference for all slots except the last one. update totals
  double *times = (double*) ALLOCA (num * sizeof(double));
  for (i=0; i < (num-1); i++) {
    double t1 = loadClockCount (event[i].cc);
    double t2 = loadClockCount (event[i+1].cc);
    times[i] = t2 - t1;
    event[i].count++;
    event[i].total_t += times[i];
    event[i].total_p += times[i]/total * 100.0;
  }

  // print report (with optional averages)
  for (i=0; i<num; i++) {
    double t,p;
    if (i < (num-1)) {
      t = times[i];
      p = t/total * 100.0;
    }
    else {
      t = total;
      p = 100.0;
    }
    fprintf (fout,"%-*s %7.2fms %6.2f%%",maxl,event[i].description,
	     t*ccunit * 1000.0, p);
    if (average && i < (num-1)) {
      fprintf (fout,"  (avg %7.2fms %6.2f%%)",
	       (event[i].total_t / event[i].count)*ccunit * 1000.0,
	       event[i].total_p / event[i].count);
    }
    fprintf (fout,"\n");
  }
  fprintf (fout,"\n");
}
<|endoftext|>