<commit_before>//===========================================================================//
// This file is part of the DIP Solver Framework.                            //
//                                                                           //
// DIP is distributed under the Eclipse Public License as part of the        //
// COIN-OR repository (http://www.coin-or.org).                              //
//                                                                           //
// Author: Matthew Galati, SAS Institute Inc. (matthew.galati@sas.com)       //
//                                                                           //
// Conceptual Design: Matthew Galati, SAS Institute Inc.                     //
//                    Ted Ralphs, Lehigh University                          //
//                                                                           //
// Copyright (C) 2002-2015, Lehigh University, Matthew Galati, Ted Ralphs    //
// All Rights Reserved.                                                      //
//===========================================================================//

//===========================================================================//
#include "UtilMacros.h"
#include "UtilParameters.h"

#include <cassert>
#include <iostream>
using namespace std;

#define MAXLINE 1024
//===========================================================================//

//TODO: need a template for usage, need application to register this, defaults
//TODO: this is an ugly combination of old C code and C++, C++-ify it

// ------------------------------------------------------------------------- //
void UtilParameters::ScanCmdLineArgs(int&   argc,
                                     char* argv[])
{
   int i, j;

   //---
   //--- if there are no arguments, return
   //---
   if (argc == 0 || argv == NULL) {
      return;
   }

   j = 1;
   string paramFileName;

   for (i = 1; i < argc; i++) {
      //---
      //--- if "--param" is specified
      //---
      if (strcmp(argv[i], "--param") == 0) {
         //---
         //---   if a filename follows the flag
         //---           grab the filename
         //---
         if (((i + 1) < argc)
               && (argv[i + 1][0] != '-' || argv[i + 1][1] != '-')) {
            paramFileName = argv[++i];
         }

         continue;
      }

      argv[j++] = argv[i];
   }

   argc = j;
   //---
   //--- load the parameter file
   //---
   LoadParamFile(paramFileName);
   //---
   //--- enter the command line flags into the parameter map
   //---   format is --SECTION:PARAMETER value
   //---
   char cmdBuf[MAXLINE];

   for (i = 1; i < argc; i++) {
      if (argv[i][0] == '-' && argv[i][1] == '-') {
         string name (argv[i] + 2);
         string value("");
         strcpy(cmdBuf, argv[i] + 2);
         char* ptr1    = strtok(cmdBuf, ":");
         char* ptr2    = strtok(NULL, ":");
         char* section = NULL;
         char* parm    = NULL;

         if (ptr2 == NULL) {
            //---
            //--- section is NULL
            //---
            parm = ptr1;
         } else {
            //---
            //--- section is not NULL
            //---
            section = ptr1;
            parm    = ptr2;
         }

         if (((i + 1) < argc) && (argv[i + 1][0] != '-' || argv[i + 1][1] != '-')) {
            value = argv[++i];
         }

         Add(section, parm, value.c_str());
         continue;
      }
   }

   //STOP - what is the point of this?
   //
   //      -----   remove all the flags from the command line
   //
   j = 1;

   for (i = 1; i < argc; i++) {
      if (argv[i][0] == '-' && argv[i][1] == '-') {
         string name (argv[i] + 2);
         string value("");

         if (((i + 1) < argc)
               && (argv[i + 1][0] != '-' || argv[i + 1][1] != '-')) {
            value = argv[++i];
         }

         continue;
      }

      argv[j++] = argv[i];
   }

   argc = j;
}

// ------------------------------------------------------------------------- //
void UtilParameters::LoadParamFile(string& paramFileName)
{
   char     buf[MAXLINE];
   char*    ptr = NULL;
   string   curSection("");
   string   bufStr    ("");
   string   name      ("");
   string   value     ("");
   //---
   //--- open the stream pointer
   //---
   ifstream is(paramFileName.c_str());

   if (!is) {
      return;
   }

   //---
   //---   foreach line in the file
   //---     skip comments (#) and blank lines
   //---
   int lineNum = 0;

   while (!is.eof()) {
      is.getline(buf, sizeof(buf) - 1);
      lineNum++;
      ptr = strchr(buf, '#');

      if (ptr != NULL) {
         *ptr = '\0';
      }

      //TODO: move all to use string? do we need buf?
      bufStr = buf;
      bufStr = UtilStrTrim(bufStr);
      strcpy(buf, bufStr.c_str());

      if (strlen(buf) < 3) {
         continue;
      }

      //---
      //--- if line is '[section]'
      //---   create a new section
      //---
      if (buf[0] == '[') {
         ptr = strchr(buf + 1, ']');

         if (ptr == NULL) {
            cerr << "UtilParameters: syntax error on line "
                 << lineNum << " '" << buf << "'" << endl;
         }

         *ptr = '\0';
         curSection = buf + 1;
         continue;
      }

      //---
      //--- if line is 'name = value'
      //---   create a new name/value pair in the current section
      //---
      ptr = strchr(buf, '=');

      if (ptr != NULL) {
         *ptr++ = '\0';
      }

      name  = buf;
      value = "1";
      name  = UtilStrTrim(name);
      name  = UtilStrToLower(name);

      if (ptr != NULL) {
         //TODO: look into old code -> value=Expand(ptr)
         value = ptr;
         value = UtilStrTrim(value);
      }

      Add(curSection, name, value);
   }

   //---
   //--- close file stream
   //---
   is.close();
}

// ------------------------------------------------------------------------- //
void UtilParameters::Add(string& sSection,
                         string& sName,
                         string& sValue)
{
   string    keyname ("");
   keyname  = UtilStrToLower(UtilStrTrim(sSection));
   keyname += "@";
   keyname += UtilStrToLower(UtilStrTrim(sName));
   //TODO: why doesn't insert override??
   // m_paramMap.insert(make_pair(keyname, UtilStrTrim(sValue)));
   m_paramMap[keyname] = UtilStrTrim(sValue);
}

// ------------------------------------------------------------------------- //
void UtilParameters::Add(const char* section,
                         const char* name,
                         const char* value)
{
   string    keyname ("");
   string    sSection("DECOMP");
   string    sName   (name);
   string    sValue  (value);

   if (section) {
      sSection = section;
   }

   keyname  = UtilStrToLower(UtilStrTrim(sSection));

   keyname += "@";
   keyname += UtilStrToLower(UtilStrTrim(sName));
   //TODO: why doesn't insert override??
   // m_paramMap.insert(make_pair(keyname, utilParam));
   m_paramMap[keyname] = UtilStrTrim(sValue);
}

// ------------------------------------------------------------------------- //
std::string* UtilParameters::Find(const char* section,
				  const char* name)
{
   string    keyname ("");
   string    sSection("DECOMP");
   string    sName   (name);

   if (section) {
      sSection = section;
      keyname  = UtilStrToLower(UtilStrTrim(sSection));
   }

   keyname += "@";
   keyname += UtilStrToLower(UtilStrTrim(sName));
   map<std::string, std::string>::iterator it;
   it = m_paramMap.find(keyname);

   if (it == m_paramMap.end()) {
      Add(section, name, "(undefined)");
      return NULL;
   } else if (it->second == "(undefined)"){
      return NULL;
   }else{
      return &(it->second);
   }
}

// ------------------------------------------------------------------------- //
string UtilParameters::GetSetting(const char* name,
                                  const std::string  defaultValue,
                                  const char* section)
{
   //---
   //--- build the qualified name using the section
   //--- if the parameter is not found, return the default
   //--- else convert the string to the appropriate type
   //---
   string* pVal = Find(section, name);

   if (pVal == NULL) {
      return defaultValue;
   }

   return *pVal;
}

// ------------------------------------------------------------------------- //
string UtilParameters::GetSetting(const char* name,
                                  const char* defaultValue,
                                  const char* section)
{
   //---
   //--- build the qualified name using the section
   //--- if the parameter is not found, return the default
   //--- else convert the string to the appropriate type
   //---
   string* pVal = Find(section, name);

   if (pVal == NULL) {
      return string(defaultValue);
   }

   return *pVal;
}

// ------------------------------------------------------------------------- //
int UtilParameters::GetSetting(const char* name,
                               const int    defaultValue,
                               const char* section)
{
   //---
   //--- build the qualified name using the section
   //--- if the parameter is not found, return the default
   //--- else convert the string to the appropriate type
   //---
   string* pVal = Find(section, name);

   if (pVal == NULL) {
      return defaultValue;
   }

   int value = atoi(pVal->c_str());
   return value;
}

// ------------------------------------------------------------------------- //
bool UtilParameters::GetSetting(const char* name,
                                const bool   defaultValue,
                                const char* section)
{
   //---
   //--- build the qualified name using the section
   //--- if the parameter is not found, return the default
   //--- else convert the string to the appropriate type
   //---
   string* pVal = Find(section, name);

   if (pVal == NULL) {
      return defaultValue;
   }

   bool value = atoi(pVal->c_str()) != 0;
   return value;
}

// ------------------------------------------------------------------------- //
long UtilParameters::GetSetting(const char* name,
                                const long   defaultValue,
                                const char* section)
{
   //---
   //--- build the qualified name using the section
   //--- if the parameter is not found, return the default
   //--- else convert the string to the appropriate type
   //---
   string* pVal = Find(section, name);

   if (pVal == NULL) {
      return defaultValue;
   }

   long value = atol(pVal->c_str());
   return value;
}

// ------------------------------------------------------------------------- //
double UtilParameters::GetSetting(const char* name,
                                  const double defaultValue,
                                  const char* section)
{
   //---
   //--- build the qualified name using the section
   //--- if the parameter is not found, return the default
   //--- else convert the string to the appropriate type
   //---
   string* pVal = Find(section, name);

   if (pVal == NULL) {
      return defaultValue;
   }

   char*    pEnd  = NULL;
   double   value = strtod(pVal->c_str(), &pEnd);
   return value;
}

#if 0
// ------------------------------------------------------------------------- //
void UtilParameters::Dump(std::ostream& os) const
{
   //
   //    -----   foreach section
   //
   SECTION_MAP::const_iterator iSection;

   for (iSection =  m_sectionMap.begin();
         iSection != m_sectionMap.end(); iSection++) {
      //
      //        -----           output the section name
      //
      std::string sectionName = iSection->first;

      if (sectionName.length() > 0) {
         os << std::endl;
         os << "[" << sectionName << "]" << std::endl;
      }

      const NV_MAP& nv = iSection->second;

      //
      //        -----           foreach parameter in the section
      //
      NV_MAP::const_iterator iParm;

      for (iParm = nv.begin(); iParm != nv.end(); iParm++) {
         const std::string& name = iParm->first;
         const std::string& value = iParm->second.second;
         //
         //    -----                   output the name/value pair
         //
         os << "[" << iParm->second.first << "] "
            << name << "    = "
            << value << std::endl;
      }
   }
}
#endif
<commit_msg>Fixing small bug in parameter setting<commit_after>//===========================================================================//
// This file is part of the DIP Solver Framework.                            //
//                                                                           //
// DIP is distributed under the Eclipse Public License as part of the        //
// COIN-OR repository (http://www.coin-or.org).                              //
//                                                                           //
// Author: Matthew Galati, SAS Institute Inc. (matthew.galati@sas.com)       //
//                                                                           //
// Conceptual Design: Matthew Galati, SAS Institute Inc.                     //
//                    Ted Ralphs, Lehigh University                          //
//                                                                           //
// Copyright (C) 2002-2015, Lehigh University, Matthew Galati, Ted Ralphs    //
// All Rights Reserved.                                                      //
//===========================================================================//

//===========================================================================//
#include "UtilMacros.h"
#include "UtilParameters.h"

#include <cassert>
#include <iostream>
using namespace std;

#define MAXLINE 1024
//===========================================================================//

//TODO: need a template for usage, need application to register this, defaults
//TODO: this is an ugly combination of old C code and C++, C++-ify it

// ------------------------------------------------------------------------- //
void UtilParameters::ScanCmdLineArgs(int&   argc,
                                     char* argv[])
{
   int i, j;

   //---
   //--- if there are no arguments, return
   //---
   if (argc == 0 || argv == NULL) {
      return;
   }

   j = 1;
   string paramFileName;

   for (i = 1; i < argc; i++) {
      //---
      //--- if "--param" is specified
      //---
      if (strcmp(argv[i], "--param") == 0) {
         //---
         //---   if a filename follows the flag
         //---           grab the filename
         //---
         if (((i + 1) < argc)
               && (argv[i + 1][0] != '-' || argv[i + 1][1] != '-')) {
            paramFileName = argv[++i];
         }

         continue;
      }

      argv[j++] = argv[i];
   }

   argc = j;
   //---
   //--- load the parameter file
   //---
   LoadParamFile(paramFileName);
   //---
   //--- enter the command line flags into the parameter map
   //---   format is --SECTION:PARAMETER value
   //---
   char cmdBuf[MAXLINE];

   for (i = 1; i < argc; i++) {
      if (argv[i][0] == '-' && argv[i][1] == '-') {
         string name (argv[i] + 2);
         string value("");
         strcpy(cmdBuf, argv[i] + 2);
         char* ptr1    = strtok(cmdBuf, ":");
         char* ptr2    = strtok(NULL, ":");
         char* section = NULL;
         char* parm    = NULL;

         if (ptr2 == NULL) {
            //---
            //--- section is NULL
            //---
            parm = ptr1;
         } else {
            //---
            //--- section is not NULL
            //---
            section = ptr1;
            parm    = ptr2;
         }

         if (((i + 1) < argc) && (argv[i + 1][0] != '-' || argv[i + 1][1] != '-')) {
            value = argv[++i];
         }

         Add(section, parm, value.c_str());
         continue;
      }
   }

   //STOP - what is the point of this?
   //
   //      -----   remove all the flags from the command line
   //
   j = 1;

   for (i = 1; i < argc; i++) {
      if (argv[i][0] == '-' && argv[i][1] == '-') {
         string name (argv[i] + 2);
         string value("");

         if (((i + 1) < argc)
               && (argv[i + 1][0] != '-' || argv[i + 1][1] != '-')) {
            value = argv[++i];
         }

         continue;
      }

      argv[j++] = argv[i];
   }

   argc = j;
}

// ------------------------------------------------------------------------- //
void UtilParameters::LoadParamFile(string& paramFileName)
{
   char     buf[MAXLINE];
   char*    ptr = NULL;
   string   curSection("");
   string   bufStr    ("");
   string   name      ("");
   string   value     ("");
   //---
   //--- open the stream pointer
   //---
   ifstream is(paramFileName.c_str());

   if (!is) {
      return;
   }

   //---
   //---   foreach line in the file
   //---     skip comments (#) and blank lines
   //---
   int lineNum = 0;

   while (!is.eof()) {
      is.getline(buf, sizeof(buf) - 1);
      lineNum++;
      ptr = strchr(buf, '#');

      if (ptr != NULL) {
         *ptr = '\0';
      }

      //TODO: move all to use string? do we need buf?
      bufStr = buf;
      bufStr = UtilStrTrim(bufStr);
      strcpy(buf, bufStr.c_str());

      if (strlen(buf) < 3) {
         continue;
      }

      //---
      //--- if line is '[section]'
      //---   create a new section
      //---
      if (buf[0] == '[') {
         ptr = strchr(buf + 1, ']');

         if (ptr == NULL) {
            cerr << "UtilParameters: syntax error on line "
                 << lineNum << " '" << buf << "'" << endl;
         }

         *ptr = '\0';
         curSection = buf + 1;
         continue;
      }

      //---
      //--- if line is 'name = value'
      //---   create a new name/value pair in the current section
      //---
      ptr = strchr(buf, '=');

      if (ptr != NULL) {
         *ptr++ = '\0';
      }

      name  = buf;
      value = "1";
      name  = UtilStrTrim(name);
      name  = UtilStrToLower(name);

      if (ptr != NULL) {
         //TODO: look into old code -> value=Expand(ptr)
         value = ptr;
         value = UtilStrTrim(value);
      }

      Add(curSection, name, value);
   }

   //---
   //--- close file stream
   //---
   is.close();
}

// ------------------------------------------------------------------------- //
void UtilParameters::Add(string& sSection,
                         string& sName,
                         string& sValue)
{
   string    keyname ("");
   keyname  = UtilStrToLower(UtilStrTrim(sSection));
   keyname += "@";
   keyname += UtilStrToLower(UtilStrTrim(sName));
   //TODO: why doesn't insert override??
   // m_paramMap.insert(make_pair(keyname, UtilStrTrim(sValue)));
   m_paramMap[keyname] = UtilStrTrim(sValue);
}

// ------------------------------------------------------------------------- //
void UtilParameters::Add(const char* section,
                         const char* name,
                         const char* value)
{
   string    keyname ("");
   string    sSection("DECOMP");
   string    sName   (name);
   string    sValue  (value);

   if (section) {
      sSection = section;
   }

   keyname  = UtilStrToLower(UtilStrTrim(sSection));

   keyname += "@";
   keyname += UtilStrToLower(UtilStrTrim(sName));
   //TODO: why doesn't insert override??
   // m_paramMap.insert(make_pair(keyname, utilParam));
   m_paramMap[keyname] = UtilStrTrim(sValue);
}

// ------------------------------------------------------------------------- //
std::string* UtilParameters::Find(const char* section,
				  const char* name)
{
   string    keyname ("");
   string    sSection("DECOMP");
   string    sName   (name);

   if (section) {
      sSection = section;
   }
   keyname  = UtilStrToLower(UtilStrTrim(sSection));

   keyname += "@";
   keyname += UtilStrToLower(UtilStrTrim(sName));
   map<std::string, std::string>::iterator it;
   it = m_paramMap.find(keyname);

   if (it == m_paramMap.end()) {
      Add(section, name, "(undefined)");
      return NULL;
   } else if (it->second == "(undefined)"){
      return NULL;
   }else{
      return &(it->second);
   }
}

// ------------------------------------------------------------------------- //
string UtilParameters::GetSetting(const char* name,
                                  const std::string  defaultValue,
                                  const char* section)
{
   //---
   //--- build the qualified name using the section
   //--- if the parameter is not found, return the default
   //--- else convert the string to the appropriate type
   //---
   string* pVal = Find(section, name);

   if (pVal == NULL) {
      return defaultValue;
   }

   return *pVal;
}

// ------------------------------------------------------------------------- //
string UtilParameters::GetSetting(const char* name,
                                  const char* defaultValue,
                                  const char* section)
{
   //---
   //--- build the qualified name using the section
   //--- if the parameter is not found, return the default
   //--- else convert the string to the appropriate type
   //---
   string* pVal = Find(section, name);

   if (pVal == NULL) {
      return string(defaultValue);
   }

   return *pVal;
}

// ------------------------------------------------------------------------- //
int UtilParameters::GetSetting(const char* name,
                               const int    defaultValue,
                               const char* section)
{
   //---
   //--- build the qualified name using the section
   //--- if the parameter is not found, return the default
   //--- else convert the string to the appropriate type
   //---
   string* pVal = Find(section, name);

   if (pVal == NULL) {
      return defaultValue;
   }

   int value = atoi(pVal->c_str());
   return value;
}

// ------------------------------------------------------------------------- //
bool UtilParameters::GetSetting(const char* name,
                                const bool   defaultValue,
                                const char* section)
{
   //---
   //--- build the qualified name using the section
   //--- if the parameter is not found, return the default
   //--- else convert the string to the appropriate type
   //---
   string* pVal = Find(section, name);

   if (pVal == NULL) {
      return defaultValue;
   }

   bool value = atoi(pVal->c_str()) != 0;
   return value;
}

// ------------------------------------------------------------------------- //
long UtilParameters::GetSetting(const char* name,
                                const long   defaultValue,
                                const char* section)
{
   //---
   //--- build the qualified name using the section
   //--- if the parameter is not found, return the default
   //--- else convert the string to the appropriate type
   //---
   string* pVal = Find(section, name);

   if (pVal == NULL) {
      return defaultValue;
   }

   long value = atol(pVal->c_str());
   return value;
}

// ------------------------------------------------------------------------- //
double UtilParameters::GetSetting(const char* name,
                                  const double defaultValue,
                                  const char* section)
{
   //---
   //--- build the qualified name using the section
   //--- if the parameter is not found, return the default
   //--- else convert the string to the appropriate type
   //---
   string* pVal = Find(section, name);

   if (pVal == NULL) {
      return defaultValue;
   }

   char*    pEnd  = NULL;
   double   value = strtod(pVal->c_str(), &pEnd);
   return value;
}

#if 0
// ------------------------------------------------------------------------- //
void UtilParameters::Dump(std::ostream& os) const
{
   //
   //    -----   foreach section
   //
   SECTION_MAP::const_iterator iSection;

   for (iSection =  m_sectionMap.begin();
         iSection != m_sectionMap.end(); iSection++) {
      //
      //        -----           output the section name
      //
      std::string sectionName = iSection->first;

      if (sectionName.length() > 0) {
         os << std::endl;
         os << "[" << sectionName << "]" << std::endl;
      }

      const NV_MAP& nv = iSection->second;

      //
      //        -----           foreach parameter in the section
      //
      NV_MAP::const_iterator iParm;

      for (iParm = nv.begin(); iParm != nv.end(); iParm++) {
         const std::string& name = iParm->first;
         const std::string& value = iParm->second.second;
         //
         //    -----                   output the name/value pair
         //
         os << "[" << iParm->second.first << "] "
            << name << "    = "
            << value << std::endl;
      }
   }
}
#endif
<|endoftext|>


<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// 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 "SurgSim/DataStructures/TriangleMesh.h"
#include "SurgSim/Framework/ObjectFactory.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Framework/SceneElement.h"
#include "SurgSim/Math/MathConvert.h"
#include "SurgSim/Math/MeshShape.h"
#include "SurgSim/Math/OdeState.h"
#include "SurgSim/Math/Shape.h"
#include "SurgSim/Physics/DeformableCollisionRepresentation.h"
#include "SurgSim/Physics/DeformableRepresentation.h"

namespace SurgSim
{
namespace Physics
{
SURGSIM_REGISTER(SurgSim::Framework::Component, SurgSim::Physics::DeformableCollisionRepresentation,
				 DeformableCollisionRepresentation);

DeformableCollisionRepresentation::DeformableCollisionRepresentation(const std::string& name) :
	SurgSim::Collision::Representation(name)
{
	SURGSIM_ADD_SERIALIZABLE_PROPERTY(DeformableCollisionRepresentation, std::shared_ptr<SurgSim::Math::Shape>,
									  Shape, getShape, setShape);
}

DeformableCollisionRepresentation::~DeformableCollisionRepresentation()
{
}

namespace
{
bool updateShapeFromOdeState(const std::shared_ptr<Math::OdeState>& odeState,
	std::shared_ptr<SurgSim::Math::MeshShape>* shape)
{
	const size_t numNodes = odeState->getNumNodes();

	SURGSIM_ASSERT((*shape)->getNumVertices() == numNodes) <<
		"The number of nodes in the deformable does not match the number of vertices in the mesh.";

	for (size_t nodeId = 0; nodeId < numNodes; ++nodeId)
	{
		(*shape)->setVertexPosition(nodeId, odeState->getPosition(nodeId));
	}

	if (!(*shape)->update())
	{
		return false;
	}

	return true;
}
}

void DeformableCollisionRepresentation::update(const double& dt)
{
	auto physicsRepresentation = m_deformable.lock();
	SURGSIM_ASSERT(nullptr != physicsRepresentation) <<
		"Failed to update.  The DeformableCollisionRepresentation either was not attached to a "
		"Physics::Representation or the Physics::Representation has expired.";

	// Write previous shape ONLY if the collision detection is continuous
	if (getCollisionDetectionType() == Collision::COLLISION_DETECTION_TYPE_CONTINUOUS &&
		!updateShapeFromOdeState(physicsRepresentation->getPreviousState(), &m_previousShape))
	{
		setLocalActive(false);
		SURGSIM_LOG_SEVERE(SurgSim::Framework::Logger::getLogger("Collision/DeformableCollisionRepresentation")) <<
			"CollisionRepresentation '" << getName() << "' " <<
			(getSceneElement() == nullptr ?
				"(of no SceneElement) " : "of SceneElement '" + getSceneElement()->getName() + "' ") <<
			"went inactive because its shape failed to update.";
	}

	// Write current shape
	if (!updateShapeFromOdeState(physicsRepresentation->getCurrentState(), &m_shape))
	{
		setLocalActive(false);
		SURGSIM_LOG_SEVERE(SurgSim::Framework::Logger::getLogger("Collision/DeformableCollisionRepresentation")) <<
			"CollisionRepresentation '" << getName() << "' " <<
			(getSceneElement() == nullptr ?
				"(of no SceneElement) " : "of SceneElement '" + getSceneElement()->getName() + "' ") <<
			"went inactive because its shape failed to update.";
	}

	invalidatePosedShapeMotion();
}

bool DeformableCollisionRepresentation::doInitialize()
{
	bool result = false;
	if (nullptr != m_shape && m_shape->isValid())
	{
		result = true;
	}

	return result;
}

bool DeformableCollisionRepresentation::doWakeUp()
{
	auto physicsRepresentation = m_deformable.lock();
	SURGSIM_ASSERT(nullptr != physicsRepresentation) <<
		"The Physics::Representation referred by this DeformableCollisionRepresentation has expired.";

	auto state = physicsRepresentation->getCurrentState();
	SURGSIM_ASSERT(nullptr != state) <<
		"DeformableRepresentation " << physicsRepresentation->getName() << " holds an empty OdeState.";
	SURGSIM_ASSERT(m_shape->getNumVertices() == state->getNumNodes()) <<
		"The number of nodes in the deformable does not match the number of vertices in the mesh.";

	update(0.0);
	return true;
}

int DeformableCollisionRepresentation::getShapeType() const
{
	SURGSIM_ASSERT(nullptr != m_shape) << "No mesh/shape assigned to DeformableCollisionRepresentation " << getName();
	return m_shape->getType();
}

void DeformableCollisionRepresentation::setShape(std::shared_ptr<SurgSim::Math::Shape> shape)
{
	SURGSIM_ASSERT(shape->getType() == SurgSim::Math::SHAPE_TYPE_MESH)
		<< "Deformable collision shape has to be a mesh.  But what passed in is " << shape->getType();

	auto meshShape = std::dynamic_pointer_cast<SurgSim::Math::MeshShape>(shape);
	m_shape = meshShape;
}

const std::shared_ptr<SurgSim::Math::Shape> DeformableCollisionRepresentation::getShape() const
{
	return m_shape;
}

void DeformableCollisionRepresentation::setDeformableRepresentation(
	std::shared_ptr<SurgSim::Physics::DeformableRepresentation>representation)
{
	m_deformable = representation;
}

const std::shared_ptr<SurgSim::Physics::DeformableRepresentation>
	DeformableCollisionRepresentation::getDeformableRepresentation() const
{
	auto physicsRepresentation = m_deformable.lock();
	SURGSIM_ASSERT(physicsRepresentation != nullptr) <<
		"Failed to get the deformable representation.  The DeformableCollisionRepresentation either was not "
		"attached to a Physics::Representation or the Physics::Representation has expired.";

	return physicsRepresentation;
}

} // namespace Physics
} // namespace SurgSim
<commit_msg>Revise DeformableCollisionRepresentation helper function signature + log msg<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// 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 "SurgSim/DataStructures/TriangleMesh.h"
#include "SurgSim/Framework/ObjectFactory.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Framework/SceneElement.h"
#include "SurgSim/Math/MathConvert.h"
#include "SurgSim/Math/MeshShape.h"
#include "SurgSim/Math/OdeState.h"
#include "SurgSim/Math/Shape.h"
#include "SurgSim/Physics/DeformableCollisionRepresentation.h"
#include "SurgSim/Physics/DeformableRepresentation.h"

namespace SurgSim
{
namespace Physics
{
SURGSIM_REGISTER(SurgSim::Framework::Component, SurgSim::Physics::DeformableCollisionRepresentation,
				 DeformableCollisionRepresentation);

DeformableCollisionRepresentation::DeformableCollisionRepresentation(const std::string& name) :
	SurgSim::Collision::Representation(name)
{
	SURGSIM_ADD_SERIALIZABLE_PROPERTY(DeformableCollisionRepresentation, std::shared_ptr<SurgSim::Math::Shape>,
									  Shape, getShape, setShape);
}

DeformableCollisionRepresentation::~DeformableCollisionRepresentation()
{
}

namespace
{
bool updateShapeFromOdeState(const Math::OdeState& odeState, SurgSim::Math::MeshShape* shape)
{
	const size_t numNodes = odeState.getNumNodes();

	SURGSIM_ASSERT(shape->getNumVertices() == numNodes) <<
		"The number of nodes in the deformable does not match the number of vertices in the mesh.";

	for (size_t nodeId = 0; nodeId < numNodes; ++nodeId)
	{
		shape->setVertexPosition(nodeId, odeState.getPosition(nodeId));
	}

	return shape->update();
}
}

void DeformableCollisionRepresentation::update(const double& dt)
{
	auto physicsRepresentation = m_deformable.lock();
	SURGSIM_ASSERT(nullptr != physicsRepresentation) <<
		"Failed to update.  The DeformableCollisionRepresentation either was not attached to a "
		"Physics::Representation or the Physics::Representation has expired.";

	// Write previous shape ONLY if the collision detection is continuous
	if (getCollisionDetectionType() == Collision::COLLISION_DETECTION_TYPE_CONTINUOUS &&
		!updateShapeFromOdeState(*physicsRepresentation->getPreviousState().get(), m_previousShape.get()))
	{
		setLocalActive(false);
		SURGSIM_LOG_SEVERE(SurgSim::Framework::Logger::getLogger("Collision/DeformableCollisionRepresentation")) <<
			"CollisionRepresentation '" << getFullName() << "' went inactive because its shape failed to update.";
	}

	// Write current shape
	if (!updateShapeFromOdeState(*physicsRepresentation->getCurrentState().get(), m_shape.get()))
	{
		setLocalActive(false);
		SURGSIM_LOG_SEVERE(Framework::Logger::getLogger("Collision/DeformableCollisionRepresentation")) <<
			"CollisionRepresentation '" << getFullName() << "' went inactive because its shape failed to update.";
	}

	invalidatePosedShapeMotion();
}

bool DeformableCollisionRepresentation::doInitialize()
{
	bool result = false;
	if (nullptr != m_shape && m_shape->isValid())
	{
		result = true;
	}

	return result;
}

bool DeformableCollisionRepresentation::doWakeUp()
{
	auto physicsRepresentation = m_deformable.lock();
	SURGSIM_ASSERT(nullptr != physicsRepresentation) <<
		"The Physics::Representation referred by this DeformableCollisionRepresentation has expired.";

	auto state = physicsRepresentation->getCurrentState();
	SURGSIM_ASSERT(nullptr != state) <<
		"DeformableRepresentation " << physicsRepresentation->getName() << " holds an empty OdeState.";
	SURGSIM_ASSERT(m_shape->getNumVertices() == state->getNumNodes()) <<
		"The number of nodes in the deformable does not match the number of vertices in the mesh.";

	update(0.0);
	return true;
}

int DeformableCollisionRepresentation::getShapeType() const
{
	SURGSIM_ASSERT(nullptr != m_shape) << "No mesh/shape assigned to DeformableCollisionRepresentation " << getName();
	return m_shape->getType();
}

void DeformableCollisionRepresentation::setShape(std::shared_ptr<SurgSim::Math::Shape> shape)
{
	SURGSIM_ASSERT(shape->getType() == SurgSim::Math::SHAPE_TYPE_MESH)
		<< "Deformable collision shape has to be a mesh.  But what passed in is " << shape->getType();

	auto meshShape = std::dynamic_pointer_cast<SurgSim::Math::MeshShape>(shape);
	m_shape = meshShape;
}

const std::shared_ptr<SurgSim::Math::Shape> DeformableCollisionRepresentation::getShape() const
{
	return m_shape;
}

void DeformableCollisionRepresentation::setDeformableRepresentation(
	std::shared_ptr<SurgSim::Physics::DeformableRepresentation>representation)
{
	m_deformable = representation;
}

const std::shared_ptr<SurgSim::Physics::DeformableRepresentation>
	DeformableCollisionRepresentation::getDeformableRepresentation() const
{
	auto physicsRepresentation = m_deformable.lock();
	SURGSIM_ASSERT(physicsRepresentation != nullptr) <<
		"Failed to get the deformable representation.  The DeformableCollisionRepresentation either was not "
		"attached to a Physics::Representation or the Physics::Representation has expired.";

	return physicsRepresentation;
}

} // namespace Physics
} // namespace SurgSim
<|endoftext|>


<commit_before>
#include "mitkManualSegmentationToSurfaceFilter.h"
#include <itksys/SystemTools.hxx>
#include "mitkDataTreeNodeFactory.h"
#include <mitkSurfaceVtkWriter.h>
#include <vtkSTLWriter.h>

#include <fstream>
/**
* Test class for ManualSegmentationToSurfaceFilter and ImageToSurface
* 1. Read an image
* 2. Create a surface
* 3. Create a Surface with all image processing facillities
*/
int mitkManualSegmentationToSurfaceFilterTest(int argc, char* argv[])
{

  if(argc==0)
  {
    std::cout<<"no file specified [FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }

  std::string path = argv[1];
  itksys::SystemTools::ConvertToUnixSlashes(path);
  std::string fileIn = path + "/BallBinary30x30x30.pic.gz";
  std::string fileOut = "BallBinary30x30x30.stl";

  fileIn = itksys::SystemTools::ConvertToOutputPath(fileIn.c_str());
  fileOut = itksys::SystemTools::ConvertToOutputPath(fileOut.c_str());
  std::cout<<"Eingabe Datei: "<<fileIn<<std::endl;
  std::cout<<"Ausgabe Datei: "<<fileOut<<std::endl;
  mitk::Image::Pointer image = NULL;
  mitk::DataTreeNodeFactory::Pointer factory = mitk::DataTreeNodeFactory::New();
  try
  {
    std::cout << "Loading file: ";
    factory->SetFileName( fileIn.c_str() );
    factory->Update();

    if(factory->GetNumberOfOutputs()<1)
    {
      std::cout<<"file could not be loaded [FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    mitk::DataTreeNode::Pointer node = factory->GetOutput( 0 );
    image = dynamic_cast<mitk::Image*>(node->GetData());
    if(image.IsNull())
    {
      std::cout<<"file not an image - test will not be applied [PASSED]"<<std::endl;
      std::cout<<"[TEST DONE]"<<std::endl;
      return EXIT_SUCCESS;
    }
  }
  catch ( itk::ExceptionObject & ex )
  {
    std::cout << "Exception: " << ex << "[FAILED]" << std::endl;
    return EXIT_FAILURE;
  }

  mitk::ManualSegmentationToSurfaceFilter::Pointer filter;
  std::cout << "Instantiat mitk::ManualSegmentationToSurfaceFilter - implicit: mitk::ImageToSurface: ";
  filter = mitk::ManualSegmentationToSurfaceFilter::New();

  if (filter.IsNull())
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  else {
  std::cout<<"[PASSED]"<<std::endl;
  }

  //Wirter instance
  mitk::SurfaceVtkWriter<vtkSTLWriter>::Pointer writer = mitk::SurfaceVtkWriter<vtkSTLWriter>::New();
  if (filter.IsNull())
  {
    std::cout<<"Instantiat SurfaceVtkWirter: [FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  else {
    writer->GlobalWarningDisplayOn();
    writer->SetFileName(fileOut.c_str());
    writer->GetVtkWriter()->SetFileTypeToBinary();

  }

  std::cout << "Create surface with default settings: ";
  filter->SetInput(image);
  writer->SetInput(filter->GetOutput());
  writer->Write();

  if( writer->GetNumberOfInputs() < 1 )
  {
     std::cout<<"[FAILED]"<<std::endl;
     writer->Delete();
     return EXIT_FAILURE;
  }
  else
  {
     std::cout<<"[PASSED]"<<std::endl;
  }

  std::cout << "Create surface all optimised settings: ";
  //configure ImageToSurfaceFilter
  filter->MedianFilter3DOn();
  filter->SetGaussianStandardDeviation(1.5);
  filter->InterpolationOn();
  filter->UseGaussianImageSmoothOn();
  filter->SetThreshold( 1 ); //if( Gauss ) --> TH manipulated for vtkMarchingCube
  filter->SetDecimate( mitk::ImageToSurfaceFilter::DecimatePro );
  filter->SetTargetReduction(0.05f);
  filter->SmoothOn();

  //filter->Update();
  writer->SetInput( filter->GetOutput() );
  if( writer->GetNumberOfInputs() < 1 )
  {
     std::cout<<"[FAILED]"<<std::endl;
     return EXIT_FAILURE;
  }
  else
  {
     std::cout<<"[PASSED]"<<std::endl;
     writer->Write();
  }

  std::cout<<"[TEST DONE]"<<std::endl;
  return EXIT_SUCCESS;
}

<commit_msg>FIX: removed explicit testimage filename<commit_after>
#include "mitkManualSegmentationToSurfaceFilter.h"
#include <itksys/SystemTools.hxx>
#include "mitkDataTreeNodeFactory.h"
#include <mitkSurfaceVtkWriter.h>
#include <vtkSTLWriter.h>

#include <fstream>
/**
* Test class for ManualSegmentationToSurfaceFilter and ImageToSurface
* 1. Read an image
* 2. Create a surface
* 3. Create a Surface with all image processing facillities
*/
int mitkManualSegmentationToSurfaceFilterTest(int argc, char* argv[])
{

  if(argc==0)
  {
    std::cout<<"no file specified [FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }

  std::string path = argv[1];
  itksys::SystemTools::ConvertToUnixSlashes(path);
  std::string fileIn = path;
  std::string fileOut = "BallBinary30x30x30.stl";

  fileIn = itksys::SystemTools::ConvertToOutputPath(fileIn.c_str());
  fileOut = itksys::SystemTools::ConvertToOutputPath(fileOut.c_str());
  std::cout<<"Eingabe Datei: "<<fileIn<<std::endl;
  std::cout<<"Ausgabe Datei: "<<fileOut<<std::endl;
  mitk::Image::Pointer image = NULL;
  mitk::DataTreeNodeFactory::Pointer factory = mitk::DataTreeNodeFactory::New();
  try
  {
    std::cout << "Loading file: ";
    factory->SetFileName( fileIn.c_str() );
    factory->Update();

    if(factory->GetNumberOfOutputs()<1)
    {
      std::cout<<"file could not be loaded [FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    mitk::DataTreeNode::Pointer node = factory->GetOutput( 0 );
    image = dynamic_cast<mitk::Image*>(node->GetData());
    if(image.IsNull())
    {
      std::cout<<"file not an image - test will not be applied [PASSED]"<<std::endl;
      std::cout<<"[TEST DONE]"<<std::endl;
      return EXIT_SUCCESS;
    }
  }
  catch ( itk::ExceptionObject & ex )
  {
    std::cout << "Exception: " << ex << "[FAILED]" << std::endl;
    return EXIT_FAILURE;
  }

  mitk::ManualSegmentationToSurfaceFilter::Pointer filter;
  std::cout << "Instantiat mitk::ManualSegmentationToSurfaceFilter - implicit: mitk::ImageToSurface: ";
  filter = mitk::ManualSegmentationToSurfaceFilter::New();

  if (filter.IsNull())
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  else {
  std::cout<<"[PASSED]"<<std::endl;
  }

  //Wirter instance
  mitk::SurfaceVtkWriter<vtkSTLWriter>::Pointer writer = mitk::SurfaceVtkWriter<vtkSTLWriter>::New();
  if (filter.IsNull())
  {
    std::cout<<"Instantiat SurfaceVtkWirter: [FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  else {
    writer->GlobalWarningDisplayOn();
    writer->SetFileName(fileOut.c_str());
    writer->GetVtkWriter()->SetFileTypeToBinary();

  }

  std::cout << "Create surface with default settings: ";
  filter->SetInput(image);
  writer->SetInput(filter->GetOutput());
  writer->Write();

  if( writer->GetNumberOfInputs() < 1 )
  {
     std::cout<<"[FAILED]"<<std::endl;
     writer->Delete();
     return EXIT_FAILURE;
  }
  else
  {
     std::cout<<"[PASSED]"<<std::endl;
  }

  std::cout << "Create surface all optimised settings: ";
  //configure ImageToSurfaceFilter
  filter->MedianFilter3DOn();
  filter->SetGaussianStandardDeviation(1.5);
  filter->InterpolationOn();
  filter->UseGaussianImageSmoothOn();
  filter->SetThreshold( 1 ); //if( Gauss ) --> TH manipulated for vtkMarchingCube
  filter->SetDecimate( mitk::ImageToSurfaceFilter::DecimatePro );
  filter->SetTargetReduction(0.05f);
  filter->SmoothOn();

  //filter->Update();
  writer->SetInput( filter->GetOutput() );
  if( writer->GetNumberOfInputs() < 1 )
  {
     std::cout<<"[FAILED]"<<std::endl;
     return EXIT_FAILURE;
  }
  else
  {
     std::cout<<"[PASSED]"<<std::endl;
     writer->Write();
  }

  std::cout<<"[TEST DONE]"<<std::endl;
  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>#include <algorithm>
#include <vector>

// Algorithm to be tested

std::vector<int> product_except_impl(std::vector<int> data)
{
  // [i] = product data[0..i[
  std::vector<int> prod_upto = {1};
  std::copy(data.begin(), data.end() -1, std::back_inserter(prod_upto));
  std::transform(prod_upto.begin(), prod_upto.end() -1
      , prod_upto.begin() +1
      , prod_upto.begin() +1
      , [](auto prod, auto cur) { return prod * cur; });

  // [size-i-1] = product data]i..size-1]
  std::vector<int> prod_from_rev = {1};
  std::copy(data.rbegin(), data.rend() -1, std::back_inserter(prod_from_rev));
  std::transform(prod_from_rev.begin(), prod_from_rev.end() -1
      , prod_from_rev.begin() +1
      , prod_from_rev.begin() +1
      , [](auto prod, auto cur) { return prod * cur; });

  for (std::size_t i {} ; i != data.size() ; ++i)
  {
    data[i] = prod_upto[i] * prod_from_rev[prod_from_rev.size()-i-1];
  }
  return data;
}

std::vector<int> product_except(std::vector<int> const& data)
{
  return product_except_impl(data);
}

#include "tests.hpp"

<commit_msg>[visual studio] Fix contiguous-data/product-except-self<commit_after>#include <algorithm>
#include <iterator>
#include <vector>

// Algorithm to be tested

std::vector<int> product_except_impl(std::vector<int> data)
{
  // [i] = product data[0..i[
  std::vector<int> prod_upto = {1};
  std::copy(data.begin(), data.end() -1, std::back_inserter(prod_upto));
  std::transform(prod_upto.begin(), prod_upto.end() -1
      , prod_upto.begin() +1
      , prod_upto.begin() +1
      , [](auto prod, auto cur) { return prod * cur; });

  // [size-i-1] = product data]i..size-1]
  std::vector<int> prod_from_rev = {1};
  std::copy(data.rbegin(), data.rend() -1, std::back_inserter(prod_from_rev));
  std::transform(prod_from_rev.begin(), prod_from_rev.end() -1
      , prod_from_rev.begin() +1
      , prod_from_rev.begin() +1
      , [](auto prod, auto cur) { return prod * cur; });

  for (std::size_t i {} ; i != data.size() ; ++i)
  {
    data[i] = prod_upto[i] * prod_from_rev[prod_from_rev.size()-i-1];
  }
  return data;
}

std::vector<int> product_except(std::vector<int> const& data)
{
  return product_except_impl(data);
}

#include "tests.hpp"

<|endoftext|>


<commit_before>#define CATCH_CONFIG_MAIN  // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"

unsigned int Factorial( unsigned int number ) {
    return number <= 1 ? number : Factorial(number-1)*number;
}

TEST_CASE( "Factorials are computed", "[factorial]" ) {
    REQUIRE( Factorial(1) == 1 );
    REQUIRE( Factorial(2) == 2 );
    REQUIRE( Factorial(3) == 6 );
    REQUIRE( Factorial(10) == 3628800 );
}
<commit_msg>Implemented first half of integration tests for string.<commit_after>#define CATCH_CONFIG_MAIN  // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include "Telemetry.hpp"
#include <fstream>
#include <sstream>
#include <iostream>

void process(TM_state * state, TM_msg * msg)
{

}

struct TM_state {
  uint8_t dummy;
};

TEST_CASE( "Valid vectors test") {
    std::ifstream valid_vectors;
    valid_vectors.open("valid_vectors.csv", std::ifstream::in);

    REQUIRE(valid_vectors.is_open());

    INFO("Test file loaded.")

    Telemetry tm;
    TM_state state;
    TM_transport * mockTransport = tm.get_transport();
    tm.sub(process, &state);

    std::string delimiter = "\t;\t";

    std::vector<std::string> serialdata;

    while(valid_vectors.good())
    {
      std::string entry;
      std::getline(valid_vectors,entry);

      std::string frametype = entry.substr(0, entry.find(delimiter));
      entry.erase(0, entry.find(delimiter) + delimiter.length());

      std::string topic = entry.substr(0, entry.find(delimiter));
      entry.erase(0, entry.find(delimiter) + delimiter.length());

      if(frametype == "string")
      {
          std::string message = entry.substr(0, entry.find(delimiter));
          entry.erase(0, entry.find(delimiter) + delimiter.length());

          std::string frame = entry.substr(0, entry.find(delimiter));
          entry.erase(0, entry.find(delimiter) + delimiter.length());

          INFO("Testing vector :" << frametype << " | "<< topic << " : " << message << " | " << frame);

          serialdata.clear();

          while(frame.size() > 1)
          {
            std::string sub = frame.substr(0, 2);
            serialdata.push_back(sub);
            std::cout<<"Data : "<<sub<<std::endl;
            frame.erase(0, 2);
          }

          INFO("Testing vector conversion finished");

          // 2 hex characters for 1 byte
          size_t frameSize = serialdata.size();

          tm.pub(topic.c_str(),message.c_str());

          int32_t bytesWritten = mockTransport->readable();

          REQUIRE(bytesWritten > 0);
          REQUIRE(bytesWritten == frameSize);

          for(size_t i = 0 ; i < serialdata.size() ; ++i)
          {
            uint8_t c;
            mockTransport->read(&c,1);

            char buffer[10];
            sprintf(buffer, "%02x", c);

            INFO("Compared " << buffer << " vs " << serialdata.at(i));

            REQUIRE(strcmp(serialdata.at(i).c_str(),buffer) == 0);
          }

          tm.update();

          // Check frame matches expected in process
      }
      else
      {
          //REQUIRE(0 == 1);
      }
    }

    valid_vectors.close();
}
<|endoftext|>


<commit_before>
#include "MechanicsFwd.hpp"
#include "NewtonEulerDS.hpp"
#include "RigidBodyDS.hpp"
#include "SiconosContactor.hpp"

#include <boost/make_shared.hpp>

RigidBodyDS::RigidBodyDS(SP::SiconosVector position,
               SP::SiconosVector velocity,
               double mass,
               SP::SimpleMatrix inertia)
  : NewtonEulerDS(position, velocity, mass, inertia)
  , _contactors(std11::make_shared<SiconosContactorSet>())
  , _useContactorInertia(true)
  , _allowSelfCollide(true)
{
}

RigidBodyDS::~RigidBodyDS()
{
}
<commit_msg>[mechanics] clean empty line<commit_after>#include "MechanicsFwd.hpp"
#include "NewtonEulerDS.hpp"
#include "RigidBodyDS.hpp"
#include "SiconosContactor.hpp"

#include <boost/make_shared.hpp>

RigidBodyDS::RigidBodyDS(SP::SiconosVector position,
               SP::SiconosVector velocity,
               double mass,
               SP::SimpleMatrix inertia)
  : NewtonEulerDS(position, velocity, mass, inertia)
  , _contactors(std11::make_shared<SiconosContactorSet>())
  , _useContactorInertia(true)
  , _allowSelfCollide(true)
{
}

RigidBodyDS::~RigidBodyDS()
{
}
<|endoftext|>


<commit_before>//===- MSP430RegisterInfo.cpp - MSP430 Register Information ---------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the MSP430 implementation of the TargetRegisterInfo class.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "msp430-reg-info"

#include "MSP430.h"
#include "MSP430MachineFunctionInfo.h"
#include "MSP430RegisterInfo.h"
#include "MSP430TargetMachine.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/ADT/BitVector.h"

using namespace llvm;

// FIXME: Provide proper call frame setup / destroy opcodes.
MSP430RegisterInfo::MSP430RegisterInfo(MSP430TargetMachine &tm,
                                       const TargetInstrInfo &tii)
  : MSP430GenRegisterInfo(MSP430::ADJCALLSTACKDOWN, MSP430::ADJCALLSTACKUP),
    TM(tm), TII(tii) {
  StackAlign = TM.getFrameInfo()->getStackAlignment();
}

const unsigned*
MSP430RegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
  static const unsigned CalleeSavedRegs[] = {
    MSP430::FPW, MSP430::R5W, MSP430::R6W, MSP430::R7W,
    MSP430::R8W, MSP430::R9W, MSP430::R10W, MSP430::R11W,
    0
  };

  return CalleeSavedRegs;
}

const TargetRegisterClass* const*
MSP430RegisterInfo::getCalleeSavedRegClasses(const MachineFunction *MF) const {
  static const TargetRegisterClass * const CalleeSavedRegClasses[] = {
    &MSP430::GR16RegClass, &MSP430::GR16RegClass,
    &MSP430::GR16RegClass, &MSP430::GR16RegClass,
    &MSP430::GR16RegClass, &MSP430::GR16RegClass,
    &MSP430::GR16RegClass, &MSP430::GR16RegClass,
    0
  };

  return CalleeSavedRegClasses;
}

BitVector
MSP430RegisterInfo::getReservedRegs(const MachineFunction &MF) const {
  BitVector Reserved(getNumRegs());

  // Mark 4 special registers as reserved.
  Reserved.set(MSP430::PCW);
  Reserved.set(MSP430::SPW);
  Reserved.set(MSP430::SRW);
  Reserved.set(MSP430::CGW);

  // Mark frame pointer as reserved if needed.
  if (hasFP(MF))
    Reserved.set(MSP430::FPW);

  return Reserved;
}

const TargetRegisterClass* MSP430RegisterInfo::getPointerRegClass() const {
  return &MSP430::GR16RegClass;
}

bool MSP430RegisterInfo::hasFP(const MachineFunction &MF) const {
  return NoFramePointerElim || MF.getFrameInfo()->hasVarSizedObjects();
}

bool MSP430RegisterInfo::hasReservedCallFrame(MachineFunction &MF) const {
  return !MF.getFrameInfo()->hasVarSizedObjects();
}

void MSP430RegisterInfo::
eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
                              MachineBasicBlock::iterator I) const {
  if (!hasReservedCallFrame(MF)) {
    // If the stack pointer can be changed after prologue, turn the
    // adjcallstackup instruction into a 'sub SPW, <amt>' and the
    // adjcallstackdown instruction into 'add SPW, <amt>'
    // TODO: consider using push / pop instead of sub + store / add
    MachineInstr *Old = I;
    uint64_t Amount = Old->getOperand(0).getImm();
    if (Amount != 0) {
      // We need to keep the stack aligned properly.  To do this, we round the
      // amount of space needed for the outgoing arguments up to the next
      // alignment boundary.
      Amount = (Amount+StackAlign-1)/StackAlign*StackAlign;

      MachineInstr *New = 0;
      if (Old->getOpcode() == getCallFrameSetupOpcode()) {
        New = BuildMI(MF, Old->getDebugLoc(),
                      TII.get(MSP430::SUB16ri), MSP430::SPW)
          .addReg(MSP430::SPW).addImm(Amount);
      } else {
        assert(Old->getOpcode() == getCallFrameDestroyOpcode());
        // factor out the amount the callee already popped.
        uint64_t CalleeAmt = Old->getOperand(1).getImm();
        Amount -= CalleeAmt;
        if (Amount)
          New = BuildMI(MF, Old->getDebugLoc(),
                        TII.get(MSP430::ADD16ri), MSP430::SPW)
            .addReg(MSP430::SPW).addImm(Amount);
      }

      if (New) {
        // The SRW implicit def is dead.
        New->getOperand(3).setIsDead();

        // Replace the pseudo instruction with a new instruction...
        MBB.insert(I, New);
      }
    }
  } else if (I->getOpcode() == getCallFrameDestroyOpcode()) {
    // If we are performing frame pointer elimination and if the callee pops
    // something off the stack pointer, add it back.
    if (uint64_t CalleeAmt = I->getOperand(1).getImm()) {
      MachineInstr *Old = I;
      MachineInstr *New =
        BuildMI(MF, Old->getDebugLoc(), TII.get(MSP430::SUB16ri),
                MSP430::SPW).addReg(MSP430::SPW).addImm(CalleeAmt);
      // The SRW implicit def is dead.
      New->getOperand(3).setIsDead();

      MBB.insert(I, New);
    }
  }

  MBB.erase(I);
}

void
MSP430RegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
                                        int SPAdj, RegScavenger *RS) const {
  assert(SPAdj == 0 && "Unexpected");

  unsigned i = 0;
  MachineInstr &MI = *II;
  MachineBasicBlock &MBB = *MI.getParent();
  MachineFunction &MF = *MBB.getParent();
  DebugLoc dl = MI.getDebugLoc();
  while (!MI.getOperand(i).isFI()) {
    ++i;
    assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
  }

  int FrameIndex = MI.getOperand(i).getIndex();

  unsigned BasePtr = (hasFP(MF) ? MSP430::FPW : MSP430::SPW);
  int Offset = MF.getFrameInfo()->getObjectOffset(FrameIndex);

  // Skip the saved PC
  Offset += 2;

  if (!hasFP(MF))
    Offset += MF.getFrameInfo()->getStackSize();
  else
    Offset += 2; // Skip the saved FPW

  // Fold imm into offset
  Offset += MI.getOperand(i+1).getImm();

  if (MI.getOpcode() == MSP430::ADD16ri) {
    // This is actually "load effective address" of the stack slot
    // instruction. We have only two-address instructions, thus we need to
    // expand it into mov + add

    MI.setDesc(TII.get(MSP430::MOV16rr));
    MI.getOperand(i).ChangeToRegister(BasePtr, false);

    if (Offset == 0)
      return;

    // We need to materialize the offset via add instruction.
    unsigned DstReg = MI.getOperand(0).getReg();
    if (Offset < 0)
      BuildMI(MBB, next(II), dl, TII.get(MSP430::SUB16ri), DstReg)
        .addReg(DstReg).addImm(-Offset);
    else
      BuildMI(MBB, next(II), dl, TII.get(MSP430::ADD16ri), DstReg)
        .addReg(DstReg).addImm(Offset);

    return;
  }

  MI.getOperand(i).ChangeToRegister(BasePtr, false);
  MI.getOperand(i+1).ChangeToImmediate(Offset);
}

void
MSP430RegisterInfo::processFunctionBeforeFrameFinalized(MachineFunction &MF)
                                                                         const {
  // Create a frame entry for the FPW register that must be saved.
  if (hasFP(MF)) {
    int FrameIdx = MF.getFrameInfo()->CreateFixedObject(2, -4);
    assert(FrameIdx == MF.getFrameInfo()->getObjectIndexBegin() &&
           "Slot for FPW register must be last in order to be found!");
    FrameIdx = 0;
  }
}

void MSP430RegisterInfo::emitPrologue(MachineFunction &MF) const {
  MachineBasicBlock &MBB = MF.front();   // Prolog goes in entry BB
  MachineFrameInfo *MFI = MF.getFrameInfo();
  MSP430MachineFunctionInfo *MSP430FI = MF.getInfo<MSP430MachineFunctionInfo>();
  MachineBasicBlock::iterator MBBI = MBB.begin();
  DebugLoc DL = (MBBI != MBB.end() ? MBBI->getDebugLoc() :
                 DebugLoc::getUnknownLoc());

  // Get the number of bytes to allocate from the FrameInfo.
  uint64_t StackSize = MFI->getStackSize();

  uint64_t NumBytes = 0;
  if (hasFP(MF)) {
    // Calculate required stack adjustment
    uint64_t FrameSize = StackSize - 2;
    NumBytes = FrameSize - MSP430FI->getCalleeSavedFrameSize();

    // Get the offset of the stack slot for the EBP register... which is
    // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
    // Update the frame offset adjustment.
    MFI->setOffsetAdjustment(-NumBytes);

    // Save FPW into the appropriate stack slot...
    BuildMI(MBB, MBBI, DL, TII.get(MSP430::PUSH16r))
      .addReg(MSP430::FPW, RegState::Kill);

    // Update FPW with the new base value...
    BuildMI(MBB, MBBI, DL, TII.get(MSP430::MOV16rr), MSP430::FPW)
      .addReg(MSP430::SPW);

    // Mark the FramePtr as live-in in every block except the entry.
    for (MachineFunction::iterator I = next(MF.begin()), E = MF.end();
         I != E; ++I)
      I->addLiveIn(MSP430::FPW);

  } else
    NumBytes = StackSize - MSP430FI->getCalleeSavedFrameSize();

  // Skip the callee-saved push instructions.
  while (MBBI != MBB.end() && (MBBI->getOpcode() == MSP430::PUSH16r))
    ++MBBI;

  if (MBBI != MBB.end())
    DL = MBBI->getDebugLoc();

  if (NumBytes) { // adjust stack pointer: SPW -= numbytes
    // If there is an SUB16ri of SPW immediately before this instruction, merge
    // the two.
    //NumBytes -= mergeSPUpdates(MBB, MBBI, true);
    // If there is an ADD16ri or SUB16ri of SPW immediately after this
    // instruction, merge the two instructions.
    // mergeSPUpdatesDown(MBB, MBBI, &NumBytes);

    if (NumBytes) {
      MachineInstr *MI =
        BuildMI(MBB, MBBI, DL, TII.get(MSP430::SUB16ri), MSP430::SPW)
        .addReg(MSP430::SPW).addImm(NumBytes);
      // The SRW implicit def is dead.
      MI->getOperand(3).setIsDead();
    }
  }
}

void MSP430RegisterInfo::emitEpilogue(MachineFunction &MF,
                                      MachineBasicBlock &MBB) const {
  const MachineFrameInfo *MFI = MF.getFrameInfo();
  MSP430MachineFunctionInfo *MSP430FI = MF.getInfo<MSP430MachineFunctionInfo>();
  MachineBasicBlock::iterator MBBI = prior(MBB.end());
  unsigned RetOpcode = MBBI->getOpcode();
  DebugLoc DL = MBBI->getDebugLoc();

  switch (RetOpcode) {
  case MSP430::RET: break;  // These are ok
  default:
    assert(0 && "Can only insert epilog into returning blocks");
  }

  // Get the number of bytes to allocate from the FrameInfo
  uint64_t StackSize = MFI->getStackSize();
  unsigned CSSize = MSP430FI->getCalleeSavedFrameSize();
  uint64_t NumBytes = 0;

  if (hasFP(MF)) {
    // Calculate required stack adjustment
    uint64_t FrameSize = StackSize - 2;
    NumBytes = FrameSize - CSSize;

    // pop FPW.
    BuildMI(MBB, MBBI, DL, TII.get(MSP430::POP16r), MSP430::FPW);
  } else
    NumBytes = StackSize - CSSize;

  // Skip the callee-saved pop instructions.
  MachineBasicBlock::iterator LastCSPop = MBBI;
  while (MBBI != MBB.begin()) {
    MachineBasicBlock::iterator PI = prior(MBBI);
    unsigned Opc = PI->getOpcode();
    if (Opc != MSP430::POP16r && !PI->getDesc().isTerminator())
      break;
    --MBBI;
  }

  DL = MBBI->getDebugLoc();

  // If there is an ADD16ri or SUB16ri of SPW immediately before this
  // instruction, merge the two instructions.
  //if (NumBytes || MFI->hasVarSizedObjects())
  //  mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);

  if (MFI->hasVarSizedObjects()) {
    assert(0 && "Not implemented yet!");
  } else {
    // adjust stack pointer back: SPW += numbytes
    if (NumBytes) {
      MachineInstr *MI =
        BuildMI(MBB, MBBI, DL, TII.get(MSP430::ADD16ri), MSP430::SPW)
        .addReg(MSP430::SPW).addImm(NumBytes);
      // The SRW implicit def is dead.
      MI->getOperand(3).setIsDead();
    }
  }
}

unsigned MSP430RegisterInfo::getRARegister() const {
  return MSP430::PCW;
}

unsigned MSP430RegisterInfo::getFrameRegister(MachineFunction &MF) const {
  return hasFP(MF) ? MSP430::FPW : MSP430::SPW;
}

int MSP430RegisterInfo::getDwarfRegNum(unsigned RegNum, bool isEH) const {
  assert(0 && "Not implemented yet!");
}

#include "MSP430GenRegisterInfo.inc"
<commit_msg>Silence warning when building without assertions.<commit_after>//===- MSP430RegisterInfo.cpp - MSP430 Register Information ---------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the MSP430 implementation of the TargetRegisterInfo class.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "msp430-reg-info"

#include "MSP430.h"
#include "MSP430MachineFunctionInfo.h"
#include "MSP430RegisterInfo.h"
#include "MSP430TargetMachine.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/ADT/BitVector.h"

using namespace llvm;

// FIXME: Provide proper call frame setup / destroy opcodes.
MSP430RegisterInfo::MSP430RegisterInfo(MSP430TargetMachine &tm,
                                       const TargetInstrInfo &tii)
  : MSP430GenRegisterInfo(MSP430::ADJCALLSTACKDOWN, MSP430::ADJCALLSTACKUP),
    TM(tm), TII(tii) {
  StackAlign = TM.getFrameInfo()->getStackAlignment();
}

const unsigned*
MSP430RegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
  static const unsigned CalleeSavedRegs[] = {
    MSP430::FPW, MSP430::R5W, MSP430::R6W, MSP430::R7W,
    MSP430::R8W, MSP430::R9W, MSP430::R10W, MSP430::R11W,
    0
  };

  return CalleeSavedRegs;
}

const TargetRegisterClass* const*
MSP430RegisterInfo::getCalleeSavedRegClasses(const MachineFunction *MF) const {
  static const TargetRegisterClass * const CalleeSavedRegClasses[] = {
    &MSP430::GR16RegClass, &MSP430::GR16RegClass,
    &MSP430::GR16RegClass, &MSP430::GR16RegClass,
    &MSP430::GR16RegClass, &MSP430::GR16RegClass,
    &MSP430::GR16RegClass, &MSP430::GR16RegClass,
    0
  };

  return CalleeSavedRegClasses;
}

BitVector
MSP430RegisterInfo::getReservedRegs(const MachineFunction &MF) const {
  BitVector Reserved(getNumRegs());

  // Mark 4 special registers as reserved.
  Reserved.set(MSP430::PCW);
  Reserved.set(MSP430::SPW);
  Reserved.set(MSP430::SRW);
  Reserved.set(MSP430::CGW);

  // Mark frame pointer as reserved if needed.
  if (hasFP(MF))
    Reserved.set(MSP430::FPW);

  return Reserved;
}

const TargetRegisterClass* MSP430RegisterInfo::getPointerRegClass() const {
  return &MSP430::GR16RegClass;
}

bool MSP430RegisterInfo::hasFP(const MachineFunction &MF) const {
  return NoFramePointerElim || MF.getFrameInfo()->hasVarSizedObjects();
}

bool MSP430RegisterInfo::hasReservedCallFrame(MachineFunction &MF) const {
  return !MF.getFrameInfo()->hasVarSizedObjects();
}

void MSP430RegisterInfo::
eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
                              MachineBasicBlock::iterator I) const {
  if (!hasReservedCallFrame(MF)) {
    // If the stack pointer can be changed after prologue, turn the
    // adjcallstackup instruction into a 'sub SPW, <amt>' and the
    // adjcallstackdown instruction into 'add SPW, <amt>'
    // TODO: consider using push / pop instead of sub + store / add
    MachineInstr *Old = I;
    uint64_t Amount = Old->getOperand(0).getImm();
    if (Amount != 0) {
      // We need to keep the stack aligned properly.  To do this, we round the
      // amount of space needed for the outgoing arguments up to the next
      // alignment boundary.
      Amount = (Amount+StackAlign-1)/StackAlign*StackAlign;

      MachineInstr *New = 0;
      if (Old->getOpcode() == getCallFrameSetupOpcode()) {
        New = BuildMI(MF, Old->getDebugLoc(),
                      TII.get(MSP430::SUB16ri), MSP430::SPW)
          .addReg(MSP430::SPW).addImm(Amount);
      } else {
        assert(Old->getOpcode() == getCallFrameDestroyOpcode());
        // factor out the amount the callee already popped.
        uint64_t CalleeAmt = Old->getOperand(1).getImm();
        Amount -= CalleeAmt;
        if (Amount)
          New = BuildMI(MF, Old->getDebugLoc(),
                        TII.get(MSP430::ADD16ri), MSP430::SPW)
            .addReg(MSP430::SPW).addImm(Amount);
      }

      if (New) {
        // The SRW implicit def is dead.
        New->getOperand(3).setIsDead();

        // Replace the pseudo instruction with a new instruction...
        MBB.insert(I, New);
      }
    }
  } else if (I->getOpcode() == getCallFrameDestroyOpcode()) {
    // If we are performing frame pointer elimination and if the callee pops
    // something off the stack pointer, add it back.
    if (uint64_t CalleeAmt = I->getOperand(1).getImm()) {
      MachineInstr *Old = I;
      MachineInstr *New =
        BuildMI(MF, Old->getDebugLoc(), TII.get(MSP430::SUB16ri),
                MSP430::SPW).addReg(MSP430::SPW).addImm(CalleeAmt);
      // The SRW implicit def is dead.
      New->getOperand(3).setIsDead();

      MBB.insert(I, New);
    }
  }

  MBB.erase(I);
}

void
MSP430RegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
                                        int SPAdj, RegScavenger *RS) const {
  assert(SPAdj == 0 && "Unexpected");

  unsigned i = 0;
  MachineInstr &MI = *II;
  MachineBasicBlock &MBB = *MI.getParent();
  MachineFunction &MF = *MBB.getParent();
  DebugLoc dl = MI.getDebugLoc();
  while (!MI.getOperand(i).isFI()) {
    ++i;
    assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
  }

  int FrameIndex = MI.getOperand(i).getIndex();

  unsigned BasePtr = (hasFP(MF) ? MSP430::FPW : MSP430::SPW);
  int Offset = MF.getFrameInfo()->getObjectOffset(FrameIndex);

  // Skip the saved PC
  Offset += 2;

  if (!hasFP(MF))
    Offset += MF.getFrameInfo()->getStackSize();
  else
    Offset += 2; // Skip the saved FPW

  // Fold imm into offset
  Offset += MI.getOperand(i+1).getImm();

  if (MI.getOpcode() == MSP430::ADD16ri) {
    // This is actually "load effective address" of the stack slot
    // instruction. We have only two-address instructions, thus we need to
    // expand it into mov + add

    MI.setDesc(TII.get(MSP430::MOV16rr));
    MI.getOperand(i).ChangeToRegister(BasePtr, false);

    if (Offset == 0)
      return;

    // We need to materialize the offset via add instruction.
    unsigned DstReg = MI.getOperand(0).getReg();
    if (Offset < 0)
      BuildMI(MBB, next(II), dl, TII.get(MSP430::SUB16ri), DstReg)
        .addReg(DstReg).addImm(-Offset);
    else
      BuildMI(MBB, next(II), dl, TII.get(MSP430::ADD16ri), DstReg)
        .addReg(DstReg).addImm(Offset);

    return;
  }

  MI.getOperand(i).ChangeToRegister(BasePtr, false);
  MI.getOperand(i+1).ChangeToImmediate(Offset);
}

void
MSP430RegisterInfo::processFunctionBeforeFrameFinalized(MachineFunction &MF)
                                                                         const {
  // Create a frame entry for the FPW register that must be saved.
  if (hasFP(MF)) {
    int FrameIdx = MF.getFrameInfo()->CreateFixedObject(2, -4);
    assert(FrameIdx == MF.getFrameInfo()->getObjectIndexBegin() &&
           "Slot for FPW register must be last in order to be found!");
    FrameIdx = 0;
  }
}

void MSP430RegisterInfo::emitPrologue(MachineFunction &MF) const {
  MachineBasicBlock &MBB = MF.front();   // Prolog goes in entry BB
  MachineFrameInfo *MFI = MF.getFrameInfo();
  MSP430MachineFunctionInfo *MSP430FI = MF.getInfo<MSP430MachineFunctionInfo>();
  MachineBasicBlock::iterator MBBI = MBB.begin();
  DebugLoc DL = (MBBI != MBB.end() ? MBBI->getDebugLoc() :
                 DebugLoc::getUnknownLoc());

  // Get the number of bytes to allocate from the FrameInfo.
  uint64_t StackSize = MFI->getStackSize();

  uint64_t NumBytes = 0;
  if (hasFP(MF)) {
    // Calculate required stack adjustment
    uint64_t FrameSize = StackSize - 2;
    NumBytes = FrameSize - MSP430FI->getCalleeSavedFrameSize();

    // Get the offset of the stack slot for the EBP register... which is
    // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
    // Update the frame offset adjustment.
    MFI->setOffsetAdjustment(-NumBytes);

    // Save FPW into the appropriate stack slot...
    BuildMI(MBB, MBBI, DL, TII.get(MSP430::PUSH16r))
      .addReg(MSP430::FPW, RegState::Kill);

    // Update FPW with the new base value...
    BuildMI(MBB, MBBI, DL, TII.get(MSP430::MOV16rr), MSP430::FPW)
      .addReg(MSP430::SPW);

    // Mark the FramePtr as live-in in every block except the entry.
    for (MachineFunction::iterator I = next(MF.begin()), E = MF.end();
         I != E; ++I)
      I->addLiveIn(MSP430::FPW);

  } else
    NumBytes = StackSize - MSP430FI->getCalleeSavedFrameSize();

  // Skip the callee-saved push instructions.
  while (MBBI != MBB.end() && (MBBI->getOpcode() == MSP430::PUSH16r))
    ++MBBI;

  if (MBBI != MBB.end())
    DL = MBBI->getDebugLoc();

  if (NumBytes) { // adjust stack pointer: SPW -= numbytes
    // If there is an SUB16ri of SPW immediately before this instruction, merge
    // the two.
    //NumBytes -= mergeSPUpdates(MBB, MBBI, true);
    // If there is an ADD16ri or SUB16ri of SPW immediately after this
    // instruction, merge the two instructions.
    // mergeSPUpdatesDown(MBB, MBBI, &NumBytes);

    if (NumBytes) {
      MachineInstr *MI =
        BuildMI(MBB, MBBI, DL, TII.get(MSP430::SUB16ri), MSP430::SPW)
        .addReg(MSP430::SPW).addImm(NumBytes);
      // The SRW implicit def is dead.
      MI->getOperand(3).setIsDead();
    }
  }
}

void MSP430RegisterInfo::emitEpilogue(MachineFunction &MF,
                                      MachineBasicBlock &MBB) const {
  const MachineFrameInfo *MFI = MF.getFrameInfo();
  MSP430MachineFunctionInfo *MSP430FI = MF.getInfo<MSP430MachineFunctionInfo>();
  MachineBasicBlock::iterator MBBI = prior(MBB.end());
  unsigned RetOpcode = MBBI->getOpcode();
  DebugLoc DL = MBBI->getDebugLoc();

  switch (RetOpcode) {
  case MSP430::RET: break;  // These are ok
  default:
    assert(0 && "Can only insert epilog into returning blocks");
  }

  // Get the number of bytes to allocate from the FrameInfo
  uint64_t StackSize = MFI->getStackSize();
  unsigned CSSize = MSP430FI->getCalleeSavedFrameSize();
  uint64_t NumBytes = 0;

  if (hasFP(MF)) {
    // Calculate required stack adjustment
    uint64_t FrameSize = StackSize - 2;
    NumBytes = FrameSize - CSSize;

    // pop FPW.
    BuildMI(MBB, MBBI, DL, TII.get(MSP430::POP16r), MSP430::FPW);
  } else
    NumBytes = StackSize - CSSize;

  // Skip the callee-saved pop instructions.
  MachineBasicBlock::iterator LastCSPop = MBBI;
  while (MBBI != MBB.begin()) {
    MachineBasicBlock::iterator PI = prior(MBBI);
    unsigned Opc = PI->getOpcode();
    if (Opc != MSP430::POP16r && !PI->getDesc().isTerminator())
      break;
    --MBBI;
  }

  DL = MBBI->getDebugLoc();

  // If there is an ADD16ri or SUB16ri of SPW immediately before this
  // instruction, merge the two instructions.
  //if (NumBytes || MFI->hasVarSizedObjects())
  //  mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);

  if (MFI->hasVarSizedObjects()) {
    assert(0 && "Not implemented yet!");
  } else {
    // adjust stack pointer back: SPW += numbytes
    if (NumBytes) {
      MachineInstr *MI =
        BuildMI(MBB, MBBI, DL, TII.get(MSP430::ADD16ri), MSP430::SPW)
        .addReg(MSP430::SPW).addImm(NumBytes);
      // The SRW implicit def is dead.
      MI->getOperand(3).setIsDead();
    }
  }
}

unsigned MSP430RegisterInfo::getRARegister() const {
  return MSP430::PCW;
}

unsigned MSP430RegisterInfo::getFrameRegister(MachineFunction &MF) const {
  return hasFP(MF) ? MSP430::FPW : MSP430::SPW;
}

int MSP430RegisterInfo::getDwarfRegNum(unsigned RegNum, bool isEH) const {
  assert(0 && "Not implemented yet!");
  return 0;
}

#include "MSP430GenRegisterInfo.inc"
<|endoftext|>


<commit_before>/**************************************************************************
 *
 * Copyright 2010 VMware, Inc.
 * All Rights Reserved.
 *
 * 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.
 *
 **************************************************************************/

/*
 * Helpers for coloring output.
 */

#ifndef _FORMATTER_HPP_
#define _FORMATTER_HPP_

#include <iostream>

namespace formatter {

/*
 * See also http://bytes.com/topic/c/answers/63822-design-question-little-c-header-colorizing-text-linux-comments-ideas
 */

class Attribute {
public:
    virtual ~Attribute() {}

    virtual void apply(std::ostream &) const {}
};

enum Color {
    RED,
    GREEN,
    BLUE,
};

class Formatter {
public:
    virtual ~Formatter() {}

    virtual Attribute *normal(void) const { return new Attribute; }
    virtual Attribute *bold(void) const { return new Attribute; }
    virtual Attribute *italic(void) const { return new Attribute; }
    virtual Attribute *strike(void) const { return new Attribute; }
    virtual Attribute *color(Color) const { return new Attribute; }
};

class AnsiAttribute : public Attribute {
protected:
    const char *escape;
public:
    AnsiAttribute(const char *_escape) : escape(_escape) {}
    void apply(std::ostream& os) const {
        os << "\33[" << escape;
    }
};

/**
 * Formatter for plain-text files which outputs ANSI escape codes. See
 * http://en.wikipedia.org/wiki/ANSI_escape_code for more information
 * concerning ANSI escape codes.
 */
class AnsiFormatter : public Formatter {
protected:
public:
    virtual Attribute *normal(void) const { return new AnsiAttribute("0m"); }
    virtual Attribute *bold(void) const { return new AnsiAttribute("1m"); }
    /* Italic is not widely supported, or worse, implemented with a reverse */
#if 0
    virtual Attribute *italic(void) const { return new AnsiAttribute("3m"); }
#endif
    virtual Attribute *strike(void) const { return new AnsiAttribute("9m"); }
    virtual Attribute *color(Color c) const {
        static const char *color_escapes[] = {
            "31m", /* red */
            "32m", /* green */
            "34m", /* blue */
        };
        return new AnsiAttribute(color_escapes[c]);
    }
};

inline std::ostream& operator<<(std::ostream& os, const Attribute *attr) {
    attr->apply(os);
    return os;
}

#ifdef _WIN32

#include <windows.h>

#ifndef COMMON_LVB_LEADING_BYTE
#define COMMON_LVB_LEADING_BYTE    0x0100
#endif

#ifndef COMMON_LVB_TRAILING_BYTE
#define COMMON_LVB_TRAILING_BYTE   0x0200
#endif

#ifndef COMMON_LVB_GRID_HORIZONTAL
#define COMMON_LVB_GRID_HORIZONTAL 0x0400
#endif

#ifndef COMMON_LVB_GRID_LVERTICAL
#define COMMON_LVB_GRID_LVERTICAL  0x0800
#endif

#ifndef COMMON_LVB_GRID_RVERTICAL
#define COMMON_LVB_GRID_RVERTICAL  0x1000
#endif

#ifndef COMMON_LVB_REVERSE_VIDEO
#define COMMON_LVB_REVERSE_VIDEO   0x4000
#endif

#ifndef COMMON_LVB_UNDERSCORE
#define COMMON_LVB_UNDERSCORE      0x8000
#endif

class WindowsAttribute : public Attribute {
protected:
    WORD wAttributes;
public:
    WindowsAttribute(WORD _wAttributes) : wAttributes(_wAttributes) {}
    void apply(std::ostream& os) const {
        DWORD nStdHandleOutput;
        if (os == std::cout) {
            nStdHandleOutput = STD_OUTPUT_HANDLE;
        } else if (os == std::cerr) {
            nStdHandleOutput = STD_ERROR_HANDLE;
        } else {
            return;
        }
        HANDLE hConsoleOutput = GetStdHandle(nStdHandleOutput);
        if (hConsoleOutput == INVALID_HANDLE_VALUE) {
            return;
        }

        SetConsoleTextAttribute(hConsoleOutput, wAttributes);
    }
};

/**
 * Formatter for the Windows Console.
 */
class WindowsFormatter : public Formatter {
protected:
public:
    virtual Attribute *normal(void) const { return new WindowsAttribute(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED); }
    virtual Attribute *bold(void) const { return new WindowsAttribute(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY); }
    virtual Attribute *italic(void) const { return new WindowsAttribute(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED); }
    virtual Attribute *strike(void) const { return new WindowsAttribute(COMMON_LVB_REVERSE_VIDEO | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED); }
    virtual Attribute *color(Color c) const {
        static const WORD color_escapes[] = {
            FOREGROUND_RED | FOREGROUND_INTENSITY,
            FOREGROUND_GREEN | FOREGROUND_INTENSITY,
            FOREGROUND_BLUE | FOREGROUND_INTENSITY,
        };
        return new WindowsAttribute(color_escapes[c]);
    }
};

#endif

inline Formatter *defaultFormatter(bool color = true) {
    if (color) {
#ifdef _WIN32
        // http://wiki.winehq.org/DeveloperFaq#detect-wine
        static HMODULE hNtDll = NULL;
        static bool bWine = false;
        if (!hNtDll) {
            hNtDll = LoadLibraryA("ntdll");
            if (hNtDll) {
                bWine = GetProcAddress(hNtDll, "wine_get_version") != NULL;
            }
        }
        if (bWine) {
            return new AnsiFormatter;
        }
        return new WindowsFormatter;
#else
        return new AnsiFormatter;
#endif
    } else {
        return new Formatter;
    }
}

} /* namespace formatter */

#endif /* _FORMATTER_HPP_ */
<commit_msg>Don't includes windows.h inside extern "C" {...}<commit_after>/**************************************************************************
 *
 * Copyright 2010 VMware, Inc.
 * All Rights Reserved.
 *
 * 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.
 *
 **************************************************************************/

/*
 * Helpers for coloring output.
 */

#ifndef _FORMATTER_HPP_
#define _FORMATTER_HPP_

#include <iostream>

#ifdef _WIN32
#include <windows.h>

#ifndef COMMON_LVB_LEADING_BYTE
#define COMMON_LVB_LEADING_BYTE    0x0100
#endif

#ifndef COMMON_LVB_TRAILING_BYTE
#define COMMON_LVB_TRAILING_BYTE   0x0200
#endif

#ifndef COMMON_LVB_GRID_HORIZONTAL
#define COMMON_LVB_GRID_HORIZONTAL 0x0400
#endif

#ifndef COMMON_LVB_GRID_LVERTICAL
#define COMMON_LVB_GRID_LVERTICAL  0x0800
#endif

#ifndef COMMON_LVB_GRID_RVERTICAL
#define COMMON_LVB_GRID_RVERTICAL  0x1000
#endif

#ifndef COMMON_LVB_REVERSE_VIDEO
#define COMMON_LVB_REVERSE_VIDEO   0x4000
#endif

#ifndef COMMON_LVB_UNDERSCORE
#define COMMON_LVB_UNDERSCORE      0x8000
#endif

#endif /* _WIN32 */

namespace formatter {

/*
 * See also http://bytes.com/topic/c/answers/63822-design-question-little-c-header-colorizing-text-linux-comments-ideas
 */

class Attribute {
public:
    virtual ~Attribute() {}

    virtual void apply(std::ostream &) const {}
};

enum Color {
    RED,
    GREEN,
    BLUE,
};

class Formatter {
public:
    virtual ~Formatter() {}

    virtual Attribute *normal(void) const { return new Attribute; }
    virtual Attribute *bold(void) const { return new Attribute; }
    virtual Attribute *italic(void) const { return new Attribute; }
    virtual Attribute *strike(void) const { return new Attribute; }
    virtual Attribute *color(Color) const { return new Attribute; }
};

class AnsiAttribute : public Attribute {
protected:
    const char *escape;
public:
    AnsiAttribute(const char *_escape) : escape(_escape) {}
    void apply(std::ostream& os) const {
        os << "\33[" << escape;
    }
};

/**
 * Formatter for plain-text files which outputs ANSI escape codes. See
 * http://en.wikipedia.org/wiki/ANSI_escape_code for more information
 * concerning ANSI escape codes.
 */
class AnsiFormatter : public Formatter {
protected:
public:
    virtual Attribute *normal(void) const { return new AnsiAttribute("0m"); }
    virtual Attribute *bold(void) const { return new AnsiAttribute("1m"); }
    /* Italic is not widely supported, or worse, implemented with a reverse */
#if 0
    virtual Attribute *italic(void) const { return new AnsiAttribute("3m"); }
#endif
    virtual Attribute *strike(void) const { return new AnsiAttribute("9m"); }
    virtual Attribute *color(Color c) const {
        static const char *color_escapes[] = {
            "31m", /* red */
            "32m", /* green */
            "34m", /* blue */
        };
        return new AnsiAttribute(color_escapes[c]);
    }
};

inline std::ostream& operator<<(std::ostream& os, const Attribute *attr) {
    attr->apply(os);
    return os;
}

#ifdef _WIN32

class WindowsAttribute : public Attribute {
protected:
    WORD wAttributes;
public:
    WindowsAttribute(WORD _wAttributes) : wAttributes(_wAttributes) {}
    void apply(std::ostream& os) const {
        DWORD nStdHandleOutput;
        if (os == std::cout) {
            nStdHandleOutput = STD_OUTPUT_HANDLE;
        } else if (os == std::cerr) {
            nStdHandleOutput = STD_ERROR_HANDLE;
        } else {
            return;
        }
        HANDLE hConsoleOutput = GetStdHandle(nStdHandleOutput);
        if (hConsoleOutput == INVALID_HANDLE_VALUE) {
            return;
        }

        SetConsoleTextAttribute(hConsoleOutput, wAttributes);
    }
};

/**
 * Formatter for the Windows Console.
 */
class WindowsFormatter : public Formatter {
protected:
public:
    virtual Attribute *normal(void) const { return new WindowsAttribute(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED); }
    virtual Attribute *bold(void) const { return new WindowsAttribute(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY); }
    virtual Attribute *italic(void) const { return new WindowsAttribute(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED); }
    virtual Attribute *strike(void) const { return new WindowsAttribute(COMMON_LVB_REVERSE_VIDEO | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED); }
    virtual Attribute *color(Color c) const {
        static const WORD color_escapes[] = {
            FOREGROUND_RED | FOREGROUND_INTENSITY,
            FOREGROUND_GREEN | FOREGROUND_INTENSITY,
            FOREGROUND_BLUE | FOREGROUND_INTENSITY,
        };
        return new WindowsAttribute(color_escapes[c]);
    }
};

#endif /* _WIN32 */

inline Formatter *defaultFormatter(bool color = true) {
    if (color) {
#ifdef _WIN32
        // http://wiki.winehq.org/DeveloperFaq#detect-wine
        static HMODULE hNtDll = NULL;
        static bool bWine = false;
        if (!hNtDll) {
            hNtDll = LoadLibraryA("ntdll");
            if (hNtDll) {
                bWine = GetProcAddress(hNtDll, "wine_get_version") != NULL;
            }
        }
        if (bWine) {
            return new AnsiFormatter;
        }
        return new WindowsFormatter;
#else
        return new AnsiFormatter;
#endif
    } else {
        return new Formatter;
    }
}

} /* namespace formatter */

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


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkWindow.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "vtkWindow.h"

// Description:
// Construct an instance of  vtkRenderWindow with its screen size
// set to 300x300, borders turned on, positioned at (0,0), double
// buffering turned on.
vtkWindow::vtkWindow()
{
  this->Size[0] = this->Size[1] = 300;
  this->Position[0] = this->Position[1] = 0;
  this->Mapped = 0;
  this->WindowName = new char[strlen("Visualization Toolkit")+1];
    strcpy( this->WindowName, "Visualization Toolkit" );
  this->Erase = 1;
  this->DoubleBuffer = 0;
}

vtkWindow::~vtkWindow()
{
  if( WindowName )
    delete [] this->WindowName;
}

void vtkWindow::SetWindowName( char * _arg )
{
  vtkDebugMacro("Debug: In " __FILE__ << ", line " << __LINE__ << "\n"
         << this->GetClassName() << " (" << this << "): setting "
         << WindowName  << " to " << _arg << "\n\n");

  if ( WindowName && _arg && (!strcmp(WindowName,_arg))) return;
  if (WindowName) delete [] WindowName;
  if( _arg )
    {
    WindowName = new char[strlen(_arg)+1];
    strcpy(WindowName,_arg);
    }
  else
    {
    WindowName = NULL;
    }
  this->Modified();
}

int *vtkWindow::GetSize()
{
  return this->Size;
}

void vtkWindow::SetSize(int a[2])
{
  this->SetSize(a[0],a[1]);
}

void vtkWindow::SetSize(int x, int y)
{
  if ((this->Size[0] != x)||(this->Size[1] != y))
    {
    this->Modified();
    this->Size[0] = x;
    this->Size[1] = y;
    }
}

int *vtkWindow::GetPosition()
{
  return this->Position;
}

void vtkWindow::SetPosition(int a[2])
{
  this->SetPosition(a[0],a[1]);
}
void vtkWindow::SetPosition(int x, int y)
{
  if ((this->Position[0] != x)||(this->Position[1] != y))
    {
    this->Modified();
    this->Position[0] = x;
    this->Position[1] = y;
    }
}

void vtkWindow::PrintSelf(ostream& os, vtkIndent indent)
{
  int *temp;

  vtkObject::PrintSelf(os,indent);

  os << indent << "Erase: " << (this->Erase ? "On\n" : "Off\n");
  os << indent << "Window Name: " << this->WindowName << "\n";
  temp = this->GetPosition();
  os << indent << "Position: (" << temp[0] << ", " << temp[1] << ")\n";
  temp = this->GetSize();
  os << indent << "Size: (" << temp[0] << ", " << temp[1] << ")\n";

}

<commit_msg>ERR:  Set WindowName to NULL after delete.  Turek.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkWindow.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "vtkWindow.h"

// Description:
// Construct an instance of  vtkRenderWindow with its screen size
// set to 300x300, borders turned on, positioned at (0,0), double
// buffering turned on.
vtkWindow::vtkWindow()
{
  this->Size[0] = this->Size[1] = 300;
  this->Position[0] = this->Position[1] = 0;
  this->Mapped = 0;
  this->WindowName = new char[strlen("Visualization Toolkit")+1];
    strcpy( this->WindowName, "Visualization Toolkit" );
  this->Erase = 1;
  this->DoubleBuffer = 0;
}

vtkWindow::~vtkWindow()
{
  if( WindowName )
    {
    delete [] this->WindowName;
	this->WindowName = NULL;
    }
}

void vtkWindow::SetWindowName( char * _arg )
{
  vtkDebugMacro("Debug: In " __FILE__ << ", line " << __LINE__ << "\n"
         << this->GetClassName() << " (" << this << "): setting "
         << WindowName  << " to " << _arg << "\n\n");

  if ( WindowName && _arg && (!strcmp(WindowName,_arg))) return;
  if (WindowName) delete [] WindowName;
  if( _arg )
    {
    WindowName = new char[strlen(_arg)+1];
    strcpy(WindowName,_arg);
    }
  else
    {
    WindowName = NULL;
    }
  this->Modified();
}

int *vtkWindow::GetSize()
{
  return this->Size;
}

void vtkWindow::SetSize(int a[2])
{
  this->SetSize(a[0],a[1]);
}

void vtkWindow::SetSize(int x, int y)
{
  if ((this->Size[0] != x)||(this->Size[1] != y))
    {
    this->Modified();
    this->Size[0] = x;
    this->Size[1] = y;
    }
}

int *vtkWindow::GetPosition()
{
  return this->Position;
}

void vtkWindow::SetPosition(int a[2])
{
  this->SetPosition(a[0],a[1]);
}
void vtkWindow::SetPosition(int x, int y)
{
  if ((this->Position[0] != x)||(this->Position[1] != y))
    {
    this->Modified();
    this->Position[0] = x;
    this->Position[1] = y;
    }
}

void vtkWindow::PrintSelf(ostream& os, vtkIndent indent)
{
  int *temp;

  vtkObject::PrintSelf(os,indent);

  os << indent << "Erase: " << (this->Erase ? "On\n" : "Off\n");
  os << indent << "Window Name: " << this->WindowName << "\n";
  temp = this->GetPosition();
  os << indent << "Position: (" << temp[0] << ", " << temp[1] << ")\n";
  temp = this->GetSize();
  os << indent << "Size: (" << temp[0] << ", " << temp[1] << ")\n";

}

<|endoftext|>