<commit_before>/*
 * Copyright (C) 2010 O01eg <o01eg@yandex.ru>
 *
 *  This file is part of Genetic Function Programming.
 *
 *  Genetic Function Programming is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Genetic Function Programming is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Genetic Function Programming.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <cstdlib>
#include <string>
#include <algorithm>
#include <locale>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include "ioobject.h"

using namespace VM;

/// \brief convert string to atomic object.
/// \param str String representation.
/// \param env Environment form creating object.
/// \return Atomic object.
Object str2atom(const std::string& str, Environment &env);

std::ostream& operator<<(std::ostream& ostr, const WeakObject& obj)
{
	std::streamsize width = ostr.width();
	ostr.width(0);
	std::stringstream os;
	/// \todo Use normal stack.
	if(! obj.IsNIL())
	{
		//const Environment& env = obj.GetEnv();
		switch(obj.GetType())
		{
			case ERROR:
				os << "ERROR ";
				break;
			case INTEGER:
				os << static_cast<int>(obj.GetValue()) << " ";
				break;
			case FUNC:
#if 0
				os << "#" << obj.GetValue() << " ";
#else
				os << obj.GetEnv().functions[obj.GetValue()].name << " ";
#endif
				break;
			case ADF:
				os << "%" << obj.GetValue() << " ";
				break;
			case PARAM:
				os << "$ ";
				break;
			case QUOTE:
				os << "QUOTE ";
				break;
			case IF:
				os << "IF ";
				break;
			case EVAL:
				os << "EVAL ";
				break;
			case LIST:
				{
					std::stack<bool> arrow_stack; // true - head, false - tail
					std::stack<WeakObject> stack;
					arrow_stack.push(true);
					stack.push(obj);
					WeakObject object(obj);
					bool arrow = true;
					//size_t level = 0;
					while(! stack.empty())
					{
						object = stack.top();
						stack.pop();
						arrow = arrow_stack.top();
						arrow_stack.pop();
						if(arrow) //head
						{
							if(object.IsNIL())
							{
								os << "NIL ";
							}
							else
							{
								if(object.GetType() == LIST)
								{
									//os << std::endl;
									/*for(size_t i = 0; i < level; i ++)
									{
										os << " ";
									}*/
									os << "( ";
									//level ++;
									stack.push(object.GetTail());
									arrow_stack.push(false);
									stack.push(object.GetHead());
									arrow_stack.push(true);
								}
								else
								{
									os << object;
								}
							}
						}
						else //tail
						{
							if(object.IsNIL())
							{
								os << ") ";
								//level --;
							}
							else
							{
								if(object.GetType() == LIST)
								{
									stack.push(object.GetTail());
									arrow_stack.push(false);
									stack.push(object.GetHead());
									arrow_stack.push(true);
								}
								else
								{
									os << ". " << object << ") ";
									//level --;
								}
							}
						}
					}
				}
				break;
			default:
				os << "ERROR ";
				break;
		}
	}
	else
	{
		os << "NIL ";
	}
	if(width < os.str().size())
	{
		//ostr << "{" << width << "}";
		ostr.write(os.str().c_str(), std::min(static_cast<size_t>(width), os.str().size()));
	}
	else
	{
		ostr << os.str();
	}
	return ostr;
}

std::istream& operator>>(std::istream& is, Object& obj)
{
	/// \todo Use normal stack.
	/// \todo Add check for empty stacks.
	Environment& env = obj.GetEnv();
	std::stack<Object> obj_stack;
	std::stack<size_t> stack;
	std::stack<bool> point_stack;
	std::stack<bool> quote_stack;
	Object obj_temp(env);
	bool reading = true;
	bool point_pair = false;
	bool quote = false;
	std::string str;
	size_t level = 0;
	while(reading)
	{
		is >> str;
		switch(str[0])
		{
			case '(':
				level ++;
				point_stack.push(point_pair);
				point_pair = false;
				quote_stack.push(quote);
				quote = false;
				break;
			case ')':
				if(point_pair)
				{
					if((! stack.empty()) && (stack.top() == level))
					{
						obj_temp = obj_stack.top();
						obj_stack.pop();
						stack.pop();
					}
					else
					{
						THROW("Wrong S-expression.");
					}
				}
				else
				{
					obj_temp = Object(env); // NIL
				}
				while((! stack.empty()) && (stack.top() == level))
				{
					stack.pop();
					obj_temp = Object(obj_stack.top(), obj_temp);
					obj_stack.pop();
					if(stack.empty())
					{
						break;
					}
				}
				level --;
				point_pair = point_stack.top();
				point_stack.pop();
				quote = quote_stack.top();
				quote_stack.pop();
				if(quote)
				{
					obj_stack.push(Object(Object(env, QUOTE), Object(obj_temp, Object(env))));
					quote = false;
				}
				else
				{
					obj_stack.push(obj_temp);
				}
				stack.push(level);
				break;
			case '.':
				point_pair = true;
				break;
			case '\'':
				quote = true;
				break;
			default:
				obj_temp = str2atom(str, env);
				if(quote)
				{
					obj_stack.push(Object(Object(env, QUOTE), Object(obj_temp, Object(env))));
					quote = false;
				}
				else
				{
					obj_stack.push(obj_temp);
				}
				stack.push(level);
				break;

		}
		reading = static_cast<bool>(level);
	}
	obj = obj_stack.top();
	return is;
}

Object str2atom(const std::string& str, Environment &env)
{
	Heap::UInt value;
	std::locale loc;
	std::string strup;
	for(std::string::const_iterator it = str.begin(); it != str.end(); it ++)
	{
		strup += std::toupper(*it, loc);
	}
	std::vector<Environment::Func>::iterator ptr = std::find(env.functions.begin(), env.functions.end(), strup);
	if(ptr != env.functions.end())
	{
		return Object(env, FUNC, ptr - env.functions.begin());
	}
	else
	{
		switch(strup[0])
		{
			case 'E':
				if(strup == "EVAL")
				{
					return Object(env, EVAL);
				}
				return Object(env, ERROR);
			case '%':
				value = atol(strup.c_str() + 1);
				return Object(env, ADF, value);
			case '$':
				return Object(env, PARAM);
			case 'Q':
				return Object(env, QUOTE);
			case 'I':
				return Object(env, IF);
			case 'N':
				return Object(env);
			default: // INTEGER or ERROR
				if((strup[0] == '-') || ((strup[0] >= '0') && (strup[0] <= '9')))
				{
					value = atol(strup.c_str());
					return Object(env, INTEGER, value);
				}
				else
				{
					return Object(env, ERROR);
				}
		}
	}
	return Object(env, ERROR);
}

<commit_msg>Fix wrong merge.<commit_after>/*
 * Copyright (C) 2010 O01eg <o01eg@yandex.ru>
 *
 *  This file is part of Genetic Function Programming.
 *
 *  Genetic Function Programming is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Genetic Function Programming is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Genetic Function Programming.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <cstdlib>
#include <string>
#include <algorithm>
#include <locale>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include "ioobject.h"

using namespace VM;

/// \brief convert string to atomic object.
/// \param str String representation.
/// \param env Environment form creating object.
/// \return Atomic object.
Object str2atom(const std::string& str, Environment &env);

std::ostream& operator<<(std::ostream& ostr, const WeakObject& obj)
{
	std::streamsize width = ostr.width();
	ostr.width(0);
	std::stringstream os;
	/// \todo Use normal stack.
	if(! obj.IsNIL())
	{
		//const Environment& env = obj.GetEnv();
		switch(obj.GetType())
		{
			case ERROR:
				os << "ERROR ";
				break;
			case INTEGER:
				os << static_cast<int>(obj.GetValue()) << " ";
				break;
			case FUNC:
#if 0
				os << "#" << obj.GetValue() << " ";
#else
				os << obj.GetEnv().functions[obj.GetValue()].name << " ";
#endif
				break;
			case ADF:
				os << "%" << obj.GetValue() << " ";
				break;
			case PARAM:
				os << "$ ";
				break;
			case QUOTE:
				os << "QUOTE ";
				break;
			case IF:
				os << "IF ";
				break;
			case EVAL:
				os << "EVAL ";
				break;
			case LIST:
				{
					std::stack<bool> arrow_stack; // true - head, false - tail
					std::stack<WeakObject> stack;
					arrow_stack.push(true);
					stack.push(obj);
					WeakObject object(obj);
					bool arrow = true;
					//size_t level = 0;
					while(! stack.empty())
					{
						object = stack.top();
						stack.pop();
						arrow = arrow_stack.top();
						arrow_stack.pop();
						if(arrow) //head
						{
							if(object.IsNIL())
							{
								os << "NIL ";
							}
							else
							{
								if(object.GetType() == LIST)
								{
									//os << std::endl;
									/*for(size_t i = 0; i < level; i ++)
									{
										os << " ";
									}*/
									os << "( ";
									//level ++;
									stack.push(object.GetTail());
									arrow_stack.push(false);
									stack.push(object.GetHead());
									arrow_stack.push(true);
								}
								else
								{
									os << object;
								}
							}
						}
						else //tail
						{
							if(object.IsNIL())
							{
								os << ") ";
								//level --;
							}
							else
							{
								if(object.GetType() == LIST)
								{
									stack.push(object.GetTail());
									arrow_stack.push(false);
									stack.push(object.GetHead());
									arrow_stack.push(true);
								}
								else
								{
									os << ". " << object << ") ";
									//level --;
								}
							}
						}
					}
				}
				break;
			default:
				os << "ERROR ";
				break;
		}
	}
	else
	{
		os << "NIL ";
	}
	if(width)
	{
		//ostr << "{" << width << "}";
		ostr.write(os.str().c_str(), std::min(static_cast<size_t>(width), os.str().size()));
	}
	else
	{
		ostr << os.str();
	}
	return ostr;
}

std::istream& operator>>(std::istream& is, Object& obj)
{
	/// \todo Use normal stack.
	/// \todo Add check for empty stacks.
	Environment& env = obj.GetEnv();
	std::stack<Object> obj_stack;
	std::stack<size_t> stack;
	std::stack<bool> point_stack;
	std::stack<bool> quote_stack;
	Object obj_temp(env);
	bool reading = true;
	bool point_pair = false;
	bool quote = false;
	std::string str;
	size_t level = 0;
	while(reading)
	{
		is >> str;
		switch(str[0])
		{
			case '(':
				level ++;
				point_stack.push(point_pair);
				point_pair = false;
				quote_stack.push(quote);
				quote = false;
				break;
			case ')':
				if(point_pair)
				{
					if((! stack.empty()) && (stack.top() == level))
					{
						obj_temp = obj_stack.top();
						obj_stack.pop();
						stack.pop();
					}
					else
					{
						THROW("Wrong S-expression.");
					}
				}
				else
				{
					obj_temp = Object(env); // NIL
				}
				while((! stack.empty()) && (stack.top() == level))
				{
					stack.pop();
					obj_temp = Object(obj_stack.top(), obj_temp);
					obj_stack.pop();
					if(stack.empty())
					{
						break;
					}
				}
				level --;
				point_pair = point_stack.top();
				point_stack.pop();
				quote = quote_stack.top();
				quote_stack.pop();
				if(quote)
				{
					obj_stack.push(Object(Object(env, QUOTE), Object(obj_temp, Object(env))));
					quote = false;
				}
				else
				{
					obj_stack.push(obj_temp);
				}
				stack.push(level);
				break;
			case '.':
				point_pair = true;
				break;
			case '\'':
				quote = true;
				break;
			default:
				obj_temp = str2atom(str, env);
				if(quote)
				{
					obj_stack.push(Object(Object(env, QUOTE), Object(obj_temp, Object(env))));
					quote = false;
				}
				else
				{
					obj_stack.push(obj_temp);
				}
				stack.push(level);
				break;

		}
		reading = static_cast<bool>(level);
	}
	obj = obj_stack.top();
	return is;
}

Object str2atom(const std::string& str, Environment &env)
{
	Heap::UInt value;
	std::locale loc;
	std::string strup;
	for(std::string::const_iterator it = str.begin(); it != str.end(); it ++)
	{
		strup += std::toupper(*it, loc);
	}
	std::vector<Environment::Func>::iterator ptr = std::find(env.functions.begin(), env.functions.end(), strup);
	if(ptr != env.functions.end())
	{
		return Object(env, FUNC, ptr - env.functions.begin());
	}
	else
	{
		switch(strup[0])
		{
			case 'E':
				if(strup == "EVAL")
				{
					return Object(env, EVAL);
				}
				return Object(env, ERROR);
			case '%':
				value = atol(strup.c_str() + 1);
				return Object(env, ADF, value);
			case '$':
				return Object(env, PARAM);
			case 'Q':
				return Object(env, QUOTE);
			case 'I':
				return Object(env, IF);
			case 'N':
				return Object(env);
			default: // INTEGER or ERROR
				if((strup[0] == '-') || ((strup[0] >= '0') && (strup[0] <= '9')))
				{
					value = atol(strup.c_str());
					return Object(env, INTEGER, value);
				}
				else
				{
					return Object(env, ERROR);
				}
		}
	}
	return Object(env, ERROR);
}

<|endoftext|>


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

 Program: FEMuS
 Module: Line
 Authors: Eugenio Aulisa and Giacomo Capodaglio

 Copyright (c) FEMuS
 All rights reserved.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#ifndef __femus_ism_Line_hpp__
#define __femus_ism_Line_hpp__

//----------------------------------------------------------------------------
// includes :
//----------------------------------------------------------------------------
#include "MarkerTypeEnum.hpp"
#include "ParallelObject.hpp"
#include "Mesh.hpp"
#include "Marker.hpp"

#include "vector"
#include "map"
#include "MyVector.hpp"

namespace femus {

  class Line : public ParallelObject {
    public:
      Line(std::vector < std::vector < double > > x, const std::vector <MarkerType> &markerType,
           Mesh *mesh, const unsigned & solType, const unsigned &size, const bool &debug = false) {

        std::vector < Marker*> particles(size);

        _dim = mesh->GetDimension();
        _size = size;

        _markerOffset.resize(_nprocs + 1);
        _markerOffset[_nprocs] = size;

        _particles.resize(size);
        _printList.resize(size);

        for(unsigned j = 0; j < size; j++) {
          particles[j] = new Marker(x[j], markerType[j], mesh, solType, debug);
        }

//         std::cout << "FIRST OF ALL" << std::endl;
//         for(unsigned i = 0; i < size; i++) {
//           std::cout << "Particle: " << i << " , " << "Processor: " << particles[i]->GetMarkerProc() << " , "
//                     << "Element: " << particles[i]->GetMarkerElement() << " " << std::endl;
//         }

        //BEGIN reorder the markers by proc
        unsigned counter = 0;
        for(unsigned iproc = 0; iproc < _nprocs; iproc++) {
          bool markersInProc = false;
          unsigned  offsetCounter = counter;
          for(unsigned j = 0; j < size; j++) {
            unsigned markerProc = particles[j]->GetMarkerProc();
            if(markerProc == iproc) {
              _particles[counter] = particles[j];
              _printList[j] = counter;
              counter++;
              markersInProc = true;
            }
          }
          if(markersInProc == true) {
            if(iproc == 0) {
              _markerOffset[iproc] = 0;
            }
            else {
              unsigned firstCounter = 0;
              for(unsigned jproc = 0; jproc < iproc; jproc++) {
                if(_markerOffset[jproc] == UINT_MAX) firstCounter++;
              }
              if(firstCounter == iproc) _markerOffset[iproc] = 0;
              else {
                _markerOffset[iproc] = offsetCounter;
              }
            }
          }
          else {
            _markerOffset[iproc] = UINT_MAX;
          }
//           std::cout << "_markerOffset[" << iproc << "]= " << _markerOffset[iproc] << std::endl;
        }
        //END reorder the markers by proc

//         std::cout << "AFTER THE REORDERING BY PROC" << std::endl;
//         for(unsigned i = 0; i < size; i++) {
//           std::cout << "Particle: " << i << " , " << "Processor: " << _particles[i]->GetMarkerProc() << " , "
//                     << "Element: " << _particles[i]->GetMarkerElement() << " " << std::endl;
//         }

        //BEGIN reorder markers also by element

        for(unsigned j = 0; j < _size; j++) {
          particles[j] = _particles[j];
        }

        unsigned* elementList = new unsigned [mesh->GetNumberOfElements()];
        std::vector < unsigned> printList(size);

        //flags to see if we already ordered by that element, 0 = not considered yet
        for(unsigned iFlag = 0; iFlag < mesh->GetNumberOfElements(); iFlag++) {
          elementList[iFlag] = 0;
        }

        printList = _printList;

        for(unsigned iproc = 0; iproc < _nprocs; iproc++) {

          if(_markerOffset[iproc] != UINT_MAX) {

            counter = 0;

            unsigned upperBound;
            bool upperBoundFound = 0;
            bool finishedProcs = 0;
            unsigned lproc = iproc + 1;
            while(upperBoundFound + finishedProcs == 0) {
              if(_markerOffset[lproc] != UINT_MAX) {
                upperBound = _markerOffset[lproc];
                upperBoundFound = 1;
              }
              else {
                if(lproc < _nprocs) lproc ++;
                else finishedProcs = 1;
              }
            }

            std::cout << "upperBound =" << upperBound << std::endl;

            for(unsigned jp = _markerOffset[iproc]; jp < upperBound; jp++) {

              unsigned jel = particles[jp]->GetMarkerElement();

              if(elementList[jel] == 0) {

                elementList[jel] = 1;

                _particles[_markerOffset[iproc] + counter] = particles[jp];
                _printList[jp] = _markerOffset[iproc] + counter;
                counter++;

                for(unsigned ip = _markerOffset[iproc]; ip < upperBound; ip++) {
                  unsigned iel = particles[ip]->GetMarkerElement();
                  if(ip != jp && iel == jel) {
                    //std::cout << " jel =" << jel << " , " << "ip = " << ip << " , " << "jp = " << jp <<  std::endl;
                    elementList[iel] = 1;
                    _particles[_markerOffset[iproc] + counter] = particles[ip];
                    _printList[ip] = _markerOffset[iproc] + counter; //TODO FIX
                    counter++;
                  }
                }
              }
            }
          }
        }

        //END reorder markers also by element

//         for(unsigned i = 0; i < _size; i++) {
//           std::cout << "_printList[ " << i << "] = " << _printList[i] << std::endl;
//         }

//         std::cout << "AFTER THE REORDERING BY ELEM" << std::endl;
//         for(unsigned i = 0; i < size; i++) {
//           std::cout << "Particle: " << i << " , " << "Processor: " << _particles[i]->GetMarkerProc() << " , "
//                     << "Element: " << _particles[i]->GetMarkerElement() << " " << std::endl;
//         }

        _line.resize(1);
        _line[0].resize(size + 1);

        for(unsigned j = 0; j < size; j++) {
          _particles[_printList[j]]->GetMarkerCoordinates(_line[0][j]);
        }
        _particles[_printList[0]]->GetMarkerCoordinates(_line[0][size]);

        for(unsigned j = 0; j < size; j++) {
          delete particles[j];
        }
        delete[] elementList;
        std::vector < unsigned > ().swap(printList);

      };

      std::vector < std::vector < std::vector < double > > > GetLine() {
        return _line;
      }

      void UpdateLine(); //TODO update the function

      void AdvectionParallel(Solution* sol, const unsigned &n, const double& T, const unsigned &order);

    private:

      std::vector < std::vector < std::vector < double > > > _line;
      std::vector < Marker*> _particles;
      std::vector < unsigned > _markerOffset;
      std::vector < unsigned > _printList;
      unsigned _size;
      unsigned _dim;

      std::vector < std::vector < std::vector < double > > > _K;

      static const double _a[4][4][4];
      static const double _b[4][4];
      static const double _c[4][4];

  };
} //end namespace femus

#endif

<commit_msg>fixed the print, now it is ok<commit_after>/*=========================================================================

 Program: FEMuS
 Module: Line
 Authors: Eugenio Aulisa and Giacomo Capodaglio

 Copyright (c) FEMuS
 All rights reserved.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#ifndef __femus_ism_Line_hpp__
#define __femus_ism_Line_hpp__

//----------------------------------------------------------------------------
// includes :
//----------------------------------------------------------------------------
#include "MarkerTypeEnum.hpp"
#include "ParallelObject.hpp"
#include "Mesh.hpp"
#include "Marker.hpp"

#include "vector"
#include "map"
#include "MyVector.hpp"

namespace femus {

  class Line : public ParallelObject {
    public:
      Line(std::vector < std::vector < double > > x, const std::vector <MarkerType> &markerType,
           Mesh *mesh, const unsigned & solType, const unsigned &size, const bool &debug = false) {

        std::vector < Marker*> particles(size);

        _dim = mesh->GetDimension();
        _size = size;

        _markerOffset.resize(_nprocs + 1);
        _markerOffset[_nprocs] = size;

        _particles.resize(size);
        _printList.resize(size);

        for(unsigned j = 0; j < size; j++) {
          particles[j] = new Marker(x[j], markerType[j], mesh, solType, debug);
        }

//         std::cout << "FIRST OF ALL" << std::endl;
//         for(unsigned i = 0; i < size; i++) {
//           std::cout << "Particle: " << i << " , " << "Processor: " << particles[i]->GetMarkerProc() << " , "
//                     << "Element: " << particles[i]->GetMarkerElement() << " " << std::endl;
//         }

        //BEGIN reorder the markers by proc
        unsigned counter = 0;
        for(unsigned iproc = 0; iproc < _nprocs; iproc++) {
          bool markersInProc = false;
          unsigned  offsetCounter = counter;
          for(unsigned j = 0; j < size; j++) {
            unsigned markerProc = particles[j]->GetMarkerProc();
            if(markerProc == iproc) {
              _particles[counter] = particles[j];
              _printList[j] = counter;
              counter++;
              markersInProc = true;
            }
          }
          if(markersInProc == true) {
            if(iproc == 0) {
              _markerOffset[iproc] = 0;
            }
            else {
              unsigned firstCounter = 0;
              for(unsigned jproc = 0; jproc < iproc; jproc++) {
                if(_markerOffset[jproc] == UINT_MAX) firstCounter++;
              }
              if(firstCounter == iproc) _markerOffset[iproc] = 0;
              else {
                _markerOffset[iproc] = offsetCounter;
              }
            }
          }
          else {
            _markerOffset[iproc] = UINT_MAX;
          }
//           std::cout << "_markerOffset[" << iproc << "]= " << _markerOffset[iproc] << std::endl;
        }
        //END reorder the markers by proc

//         std::cout << "AFTER THE REORDERING BY PROC" << std::endl;
//         for(unsigned i = 0; i < size; i++) {
//           std::cout << "Particle: " << i << " , " << "Processor: " << _particles[i]->GetMarkerProc() << " , "
//                     << "Element: " << _particles[i]->GetMarkerElement() << " " << std::endl;
//         }

//         for(unsigned i = 0; i < _size; i++) {
//           std::cout << "_printList[ " << i << "] = " << _printList[i] << std::endl;
//         }
//
//
//         std::cout << " ------------------------------------------------------------------------------------------------ " << std::endl;

        //BEGIN reorder markers also by element

        for(unsigned j = 0; j < _size; j++) {
          particles[j] = _particles[j];
        }

        unsigned* elementList = new unsigned [mesh->GetNumberOfElements()];
        std::vector < unsigned> printList(size);

        //flags to see if we already ordered by that element, 0 = not considered yet
        for(unsigned iFlag = 0; iFlag < mesh->GetNumberOfElements(); iFlag++) {
          elementList[iFlag] = 0;
        }

        printList = _printList;

        for(unsigned iproc = 0; iproc < _nprocs; iproc++) {

          if(_markerOffset[iproc] != UINT_MAX) {

            counter = 0;

            unsigned upperBound;
            bool upperBoundFound = 0;
            bool finishedProcs = 0;
            unsigned lproc = iproc + 1;
            while(upperBoundFound + finishedProcs == 0) {
              if(_markerOffset[lproc] != UINT_MAX) {
                upperBound = _markerOffset[lproc];
                upperBoundFound = 1;
              }
              else {
                if(lproc < _nprocs) lproc ++;
                else finishedProcs = 1;
              }
            }

            //std::cout << "upperBound =" << upperBound << std::endl;

            for(unsigned jp = _markerOffset[iproc]; jp < upperBound; jp++) {

              unsigned jel = particles[jp]->GetMarkerElement();

              if(elementList[jel] == 0) {

                elementList[jel] = 1;

                _particles[_markerOffset[iproc] + counter] = particles[jp];
                for(unsigned iList = 0; iList < size; iList++) {
                  if(printList[iList] == jp) {
                    _printList[iList] = _markerOffset[iproc] + counter;
                    break;
                  }
                }
                counter++;

                for(unsigned ip = _markerOffset[iproc]; ip < upperBound; ip++) {
                  unsigned iel = particles[ip]->GetMarkerElement();
                  if(ip != jp && iel == jel) {
                    //std::cout << " jel =" << jel << " , " << "ip = " << ip << " , " << "jp = " << jp <<  std::endl;
                    elementList[iel] = 1;
                    _particles[_markerOffset[iproc] + counter] = particles[ip];
                    for(unsigned iList = 0; iList < size; iList++) {
                      if(printList[iList] == ip) {
                        _printList[iList] = _markerOffset[iproc] + counter;
                        break;
                      }
                    }
                    counter++;
                  }
                }
              }
            }
          }
        }

        //END reorder markers also by element

//         for(unsigned i = 0; i < _size; i++) {
//           std::cout << "_printList[ " << i << "] = " << _printList[i] << std::endl;
//         }

//         std::cout << "AFTER THE REORDERING BY ELEM" << std::endl;
//         for(unsigned i = 0; i < size; i++) {
//           std::cout << "Particle: " << i << " , " << "Processor: " << _particles[i]->GetMarkerProc() << " , "
//                     << "Element: " << _particles[i]->GetMarkerElement() << " " << std::endl;
//         }

        _line.resize(1);
        _line[0].resize(size + 1);

        for(unsigned j = 0; j < size; j++) {
          _particles[_printList[j]]->GetMarkerCoordinates(_line[0][j]);
        }
        _particles[_printList[0]]->GetMarkerCoordinates(_line[0][size]);

        for(unsigned j = 0; j < size; j++) {
          delete particles[j];
        }
        delete[] elementList;
        std::vector < unsigned > ().swap(printList);

      };

      std::vector < std::vector < std::vector < double > > > GetLine() {
        return _line;
      }

      void UpdateLine(); //TODO update the function

      void AdvectionParallel(Solution* sol, const unsigned &n, const double& T, const unsigned &order);

    private:

      std::vector < std::vector < std::vector < double > > > _line;
      std::vector < Marker*> _particles;
      std::vector < unsigned > _markerOffset;
      std::vector < unsigned > _printList;
      unsigned _size;
      unsigned _dim;

      std::vector < std::vector < std::vector < double > > > _K;

      static const double _a[4][4][4];
      static const double _b[4][4];
      static const double _c[4][4];

  };
} //end namespace femus

#endif

<|endoftext|>


<commit_before>/* Copyright 1994, 1995 by Abacus Research and
 * Development, Inc.  All rights reserved.
 */

#if !defined(NDEBUG)

#include "rsys/common.h"

#include "DialogMgr.h"
#include "QuickDraw.h"

#include "rsys/cquick.h"
#include "rsys/region.h"
#include "rsys/stdbits.h"
#include "rsys/dump.h"

#include "rsys/iv.h"

#include <unistd.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>

using namespace Executor;

#define print_errno_error_message(call, msg)   \
    ({                                         \
        fprintf(stderr, "%s:%d; %s: %s; %s\n", \
                __FILE__, __LINE__,            \
                call, strerror(errno),         \
                msg);                          \
    })

void send_image(int width, int height,
                int row_bytes, int send_row_bytes,
                char *base_addr,
                CTabHandle ctab)
{
    image_header_t header;

    int sockfd, retval, i;
    struct sockaddr_in srv_addr;
    char hostname[1024];
    struct hostent *host;

    header.width = width;
    header.height = height;
    header.row_bytes = send_row_bytes;

    memset(header.image_color_map, '\0', sizeof header.image_color_map);

    for(i = 0; i <= CTAB_SIZE(ctab); i++)
    {
        color_t *color;
        ColorSpec *color_spec;

        color = &header.image_color_map[i];
        color_spec = &CTAB_TABLE(ctab)[i];

        color->red = CW(color_spec->rgb.red);
        color->green = CW(color_spec->rgb.green);
        color->blue = CW(color_spec->rgb.blue);
    }
    /* connect to server, and send */
    gethostname(hostname, 1024);
    host = gethostbyname(hostname);

    sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(sockfd < 0)
    {
        print_errno_error_message("socket", "unable to send image");
        return;
    }

    srv_addr.sin_family = AF_INET;
    srv_addr.sin_port = PORT;
    srv_addr.sin_addr = *((struct in_addr *)host->h_addr);
    retval = connect(sockfd, (struct sockaddr *)&srv_addr,
                     sizeof srv_addr);
    if(retval < 0)
    {
        print_errno_error_message("connect", "unable to send image");
        return;
    }

    retval = write(sockfd, &header, sizeof header);
    if(retval < 0)
    {
        print_errno_error_message("write", "unable to send image");
        return;
    }

    for(i = 0; i < height; i++)
    {
        retval = write(sockfd, base_addr, send_row_bytes);
        base_addr += row_bytes;
        if(retval < 0)
        {
            print_errno_error_message("write", "unable to send image");
            return;
        }
    }

    close(sockfd);
}

void dump_image(BitMap *bogo_bitmap, Rect *rect);

void dump_grafport_image(GrafPort *port)
{
    Rect r, bounds;

    r = PORT_RECT(port);
    bounds = PORT_BOUNDS(port);
    OffsetRect(&bounds,
               CW(r.left) - CW(bounds.left),
               CW(r.top) - CW(bounds.top));
    SectRect(&r, &bounds, &r);
    dump_image(&port->portBits, &r);
}

void dump_image(BitMap *bogo_bitmap, Rect *rect)
{
    struct cleanup_info cleanup;
    int width, height, row_bytes;
    char *base_addr, *_base_addr;
    PixMap dummy_space;
    PixMap *pixmap = &dummy_space;
    int depth;
    int map_row_bytes;

    canonicalize_bogo_map(bogo_bitmap, &pixmap, &cleanup);

    width = RECT_WIDTH(rect);
    height = RECT_HEIGHT(rect);

    /* destination must be 8bpp */
    depth = CW(pixmap->pixelSize);
    if(depth != 8)
    {
        int map_width, map_height;
        static PixMap new_pixmap;
        ColorTable *conv_table;
        int i;

        map_width = RECT_WIDTH(&pixmap->bounds);
        map_height = RECT_HEIGHT(&pixmap->bounds);

        map_row_bytes = ((width * 8 + 31) / 32) * 4;
        base_addr = (char *)alloca(map_row_bytes * height);

        new_pixmap.rowBytes = CW(map_row_bytes);
        new_pixmap.baseAddr = RM((Ptr)base_addr);

        new_pixmap.pixelSize = CWC(8);
        new_pixmap.cmpCount = CWC(1);
        new_pixmap.cmpSize = CWC(8);

        new_pixmap.pmTable = NULL;

        conv_table = (ColorTable *)alloca(CTAB_STORAGE_FOR_SIZE(1 << depth));
        for(i = 0; i < (1 << depth); i++)
            conv_table->ctTable[i].value = CW(i);

        convert_pixmap(pixmap, &new_pixmap, rect,
                       conv_table);
        new_pixmap.pmTable = pixmap->pmTable;
        pixmap = &new_pixmap;
    }
    else
    {
        map_row_bytes = CW(pixmap->rowBytes
                           & ~ROWBYTES_FLAG_BITS_X);
        base_addr = (char *)MR(pixmap->baseAddr);
    }

    row_bytes = width;
    _base_addr
        = &base_addr[(CW(rect->top) - CW(pixmap->bounds.top)) * map_row_bytes
                     + (CW(rect->left) - CW(pixmap->bounds.left))];
    send_image(width, height,
               map_row_bytes, row_bytes,
               _base_addr,
               MR(pixmap->pmTable));

    canonicalize_bogo_map_cleanup((BitMap *)&pixmap, &cleanup);
}

void dump_rgn_as_image(RgnHandle rh)
{
    BitMap bm;
    int row_bytes;
    char *baseaddr;

    bm.bounds = RGN_BBOX(rh);
    row_bytes = ((RECT_WIDTH(&bm.bounds) + 31) / 32) * 4;
    bm.rowBytes = CW(row_bytes);
    baseaddr = (char *)alloca(row_bytes * RECT_HEIGHT(&bm.bounds));
    bm.baseAddr = RM((Ptr)baseaddr);
    memset(baseaddr, '\377', row_bytes * RECT_HEIGHT(&bm.bounds));

    CopyBits(&bm, &bm,
             &bm.bounds, &bm.bounds,
             srcXor, rh);

    dump_image(&bm, &bm.bounds);
}

#endif /* !NDEBUG */
<commit_msg>replace a ({}) with do {} while(0)<commit_after>/* Copyright 1994, 1995 by Abacus Research and
 * Development, Inc.  All rights reserved.
 */

#if !defined(NDEBUG)

#include "rsys/common.h"

#include "DialogMgr.h"
#include "QuickDraw.h"

#include "rsys/cquick.h"
#include "rsys/region.h"
#include "rsys/stdbits.h"
#include "rsys/dump.h"

#include "rsys/iv.h"

#include <unistd.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>

using namespace Executor;

#define print_errno_error_message(call, msg)   \
    do {                                       \
        fprintf(stderr, "%s:%d; %s: %s; %s\n", \
                __FILE__, __LINE__,            \
                call, strerror(errno),         \
                msg);                          \
    } while(0)

void send_image(int width, int height,
                int row_bytes, int send_row_bytes,
                char *base_addr,
                CTabHandle ctab)
{
    image_header_t header;

    int sockfd, retval, i;
    struct sockaddr_in srv_addr;
    char hostname[1024];
    struct hostent *host;

    header.width = width;
    header.height = height;
    header.row_bytes = send_row_bytes;

    memset(header.image_color_map, '\0', sizeof header.image_color_map);

    for(i = 0; i <= CTAB_SIZE(ctab); i++)
    {
        color_t *color;
        ColorSpec *color_spec;

        color = &header.image_color_map[i];
        color_spec = &CTAB_TABLE(ctab)[i];

        color->red = CW(color_spec->rgb.red);
        color->green = CW(color_spec->rgb.green);
        color->blue = CW(color_spec->rgb.blue);
    }
    /* connect to server, and send */
    gethostname(hostname, 1024);
    host = gethostbyname(hostname);

    sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(sockfd < 0)
    {
        print_errno_error_message("socket", "unable to send image");
        return;
    }

    srv_addr.sin_family = AF_INET;
    srv_addr.sin_port = PORT;
    srv_addr.sin_addr = *((struct in_addr *)host->h_addr);
    retval = connect(sockfd, (struct sockaddr *)&srv_addr,
                     sizeof srv_addr);
    if(retval < 0)
    {
        print_errno_error_message("connect", "unable to send image");
        return;
    }

    retval = write(sockfd, &header, sizeof header);
    if(retval < 0)
    {
        print_errno_error_message("write", "unable to send image");
        return;
    }

    for(i = 0; i < height; i++)
    {
        retval = write(sockfd, base_addr, send_row_bytes);
        base_addr += row_bytes;
        if(retval < 0)
        {
            print_errno_error_message("write", "unable to send image");
            return;
        }
    }

    close(sockfd);
}

void dump_image(BitMap *bogo_bitmap, Rect *rect);

void dump_grafport_image(GrafPort *port)
{
    Rect r, bounds;

    r = PORT_RECT(port);
    bounds = PORT_BOUNDS(port);
    OffsetRect(&bounds,
               CW(r.left) - CW(bounds.left),
               CW(r.top) - CW(bounds.top));
    SectRect(&r, &bounds, &r);
    dump_image(&port->portBits, &r);
}

void dump_image(BitMap *bogo_bitmap, Rect *rect)
{
    struct cleanup_info cleanup;
    int width, height, row_bytes;
    char *base_addr, *_base_addr;
    PixMap dummy_space;
    PixMap *pixmap = &dummy_space;
    int depth;
    int map_row_bytes;

    canonicalize_bogo_map(bogo_bitmap, &pixmap, &cleanup);

    width = RECT_WIDTH(rect);
    height = RECT_HEIGHT(rect);

    /* destination must be 8bpp */
    depth = CW(pixmap->pixelSize);
    if(depth != 8)
    {
        int map_width, map_height;
        static PixMap new_pixmap;
        ColorTable *conv_table;
        int i;

        map_width = RECT_WIDTH(&pixmap->bounds);
        map_height = RECT_HEIGHT(&pixmap->bounds);

        map_row_bytes = ((width * 8 + 31) / 32) * 4;
        base_addr = (char *)alloca(map_row_bytes * height);

        new_pixmap.rowBytes = CW(map_row_bytes);
        new_pixmap.baseAddr = RM((Ptr)base_addr);

        new_pixmap.pixelSize = CWC(8);
        new_pixmap.cmpCount = CWC(1);
        new_pixmap.cmpSize = CWC(8);

        new_pixmap.pmTable = NULL;

        conv_table = (ColorTable *)alloca(CTAB_STORAGE_FOR_SIZE(1 << depth));
        for(i = 0; i < (1 << depth); i++)
            conv_table->ctTable[i].value = CW(i);

        convert_pixmap(pixmap, &new_pixmap, rect,
                       conv_table);
        new_pixmap.pmTable = pixmap->pmTable;
        pixmap = &new_pixmap;
    }
    else
    {
        map_row_bytes = CW(pixmap->rowBytes
                           & ~ROWBYTES_FLAG_BITS_X);
        base_addr = (char *)MR(pixmap->baseAddr);
    }

    row_bytes = width;
    _base_addr
        = &base_addr[(CW(rect->top) - CW(pixmap->bounds.top)) * map_row_bytes
                     + (CW(rect->left) - CW(pixmap->bounds.left))];
    send_image(width, height,
               map_row_bytes, row_bytes,
               _base_addr,
               MR(pixmap->pmTable));

    canonicalize_bogo_map_cleanup((BitMap *)&pixmap, &cleanup);
}

void dump_rgn_as_image(RgnHandle rh)
{
    BitMap bm;
    int row_bytes;
    char *baseaddr;

    bm.bounds = RGN_BBOX(rh);
    row_bytes = ((RECT_WIDTH(&bm.bounds) + 31) / 32) * 4;
    bm.rowBytes = CW(row_bytes);
    baseaddr = (char *)alloca(row_bytes * RECT_HEIGHT(&bm.bounds));
    bm.baseAddr = RM((Ptr)baseaddr);
    memset(baseaddr, '\377', row_bytes * RECT_HEIGHT(&bm.bounds));

    CopyBits(&bm, &bm,
             &bm.bounds, &bm.bounds,
             srcXor, rh);

    dump_image(&bm, &bm.bounds);
}

#endif /* !NDEBUG */
<|endoftext|>


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

#ifndef __FRAMEWORK_JOBS_JOBURL_HXX_
#define __FRAMEWORK_JOBS_JOBURL_HXX_

//_______________________________________
// my own includes

#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif

#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif

#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif

//_______________________________________
// interface includes

//_______________________________________
// other includes

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

//_______________________________________
// namespace

namespace framework{

//_______________________________________
// const

#define JOBURL_PROTOCOL_STR        "vnd.sun.star.job:"
#define JOBURL_PROTOCOL_LEN        17

#define JOBURL_EVENT_STR           "event="
#define JOBURL_EVENT_LEN           6

#define JOBURL_ALIAS_STR           "alias="
#define JOBURL_ALIAS_LEN           6

#define JOBURL_SERVICE_STR         "service="
#define JOBURL_SERVICE_LEN         8

#define JOBURL_PART_SEPERATOR      ';'
#define JOBURL_PARTARGS_SEPERATOR  ','

//_______________________________________
/**
    @short  can be used to parse, validate and work with job URL's
    @descr  Job URLs are specified by the following syntax:
                vnd.sun.star.job:{[event=<name>]|[alias=<name>]|[service=<name>]}
            This class can analyze this structure and seperate it into his different parts.
            After doing that these parts are accessible by the methods of this class.
 */
class JobURL : private ThreadHelpBase
{
    //___________________________________
    // types

    private:

        /**
            possible states of a job URL
            Note: These values are used in combination. So they must be
            values in form 2^n.
         */
        enum ERequest
        {
            /// mark a job URL as not valid
            E_UNKNOWN = 0,
            /// it's an event
            E_EVENT   = 1,
            /// it's an alias
            E_ALIAS   = 2,
            /// it's a service
            E_SERVICE = 4
        };

    //___________________________________
    // types

    private:

        /** knows the state of this URL instance */
        sal_uInt32 m_eRequest;

        /** holds the event part of a job URL */
        ::rtl::OUString m_sEvent;

        /** holds the alias part of a job URL */
        ::rtl::OUString m_sAlias;

        /** holds the service part of a job URL */
        ::rtl::OUString m_sService;

        /** holds the event arguments */
        ::rtl::OUString m_sEventArgs;

        /** holds the alias arguments */
        ::rtl::OUString m_sAliasArgs;

        /** holds the service arguments */
        ::rtl::OUString m_sServiceArgs;

    //___________________________________
    // native interface

    public:

                 JobURL        ( const ::rtl::OUString& sURL         );
        sal_Bool isValid       (                                     ) const;
        sal_Bool getEvent      (       ::rtl::OUString& sEvent       ) const;
        sal_Bool getAlias      (       ::rtl::OUString& sAlias       ) const;
        sal_Bool getService    (       ::rtl::OUString& sService     ) const;
        sal_Bool getEventArgs  (       ::rtl::OUString& sEventArgs   ) const;
        sal_Bool getAliasArgs  (       ::rtl::OUString& sAliasArgs   ) const;
        sal_Bool getServiceArgs(       ::rtl::OUString& sServiceArgs ) const;

    //___________________________________
    // private helper

    private:

        static sal_Bool implst_split( const ::rtl::OUString& sPart           ,
                                      const sal_Char*        pPartIdentifier ,
                                            sal_Int32        nPartLength     ,
                                            ::rtl::OUString& rPartValue      ,
                                            ::rtl::OUString& rPartArguments  );

    //___________________________________
    // debug methods!

    #ifdef ENABLE_COMPONENT_SELF_CHECK

    public:
        static void impldbg_checkIt();

    private:
        static void impldbg_checkURL( const sal_Char*  pURL                 ,
                                            sal_uInt32 eExpectedPart        ,
                                      const sal_Char*  pExpectedEvent       ,
                                      const sal_Char*  pExpectedAlias       ,
                                      const sal_Char*  pExpectedService     ,
                                      const sal_Char*  pExpectedEventArgs   ,
                                      const sal_Char*  pExpectedAliasArgs   ,
                                      const sal_Char*  pExpectedServiceArgs );
        ::rtl::OUString impldbg_toString() const;

    #endif // ENABLE_COMPONENT_SELF_CHECK
};

} // namespace framework

#endif // __FRAMEWORK_JOBS_JOBURL_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.502); FILE MERGED 2005/09/05 13:05:01 rt 1.2.502.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: joburl.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 00:23:36 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef __FRAMEWORK_JOBS_JOBURL_HXX_
#define __FRAMEWORK_JOBS_JOBURL_HXX_

//_______________________________________
// my own includes

#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif

#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif

#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif

//_______________________________________
// interface includes

//_______________________________________
// other includes

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

//_______________________________________
// namespace

namespace framework{

//_______________________________________
// const

#define JOBURL_PROTOCOL_STR        "vnd.sun.star.job:"
#define JOBURL_PROTOCOL_LEN        17

#define JOBURL_EVENT_STR           "event="
#define JOBURL_EVENT_LEN           6

#define JOBURL_ALIAS_STR           "alias="
#define JOBURL_ALIAS_LEN           6

#define JOBURL_SERVICE_STR         "service="
#define JOBURL_SERVICE_LEN         8

#define JOBURL_PART_SEPERATOR      ';'
#define JOBURL_PARTARGS_SEPERATOR  ','

//_______________________________________
/**
    @short  can be used to parse, validate and work with job URL's
    @descr  Job URLs are specified by the following syntax:
                vnd.sun.star.job:{[event=<name>]|[alias=<name>]|[service=<name>]}
            This class can analyze this structure and seperate it into his different parts.
            After doing that these parts are accessible by the methods of this class.
 */
class JobURL : private ThreadHelpBase
{
    //___________________________________
    // types

    private:

        /**
            possible states of a job URL
            Note: These values are used in combination. So they must be
            values in form 2^n.
         */
        enum ERequest
        {
            /// mark a job URL as not valid
            E_UNKNOWN = 0,
            /// it's an event
            E_EVENT   = 1,
            /// it's an alias
            E_ALIAS   = 2,
            /// it's a service
            E_SERVICE = 4
        };

    //___________________________________
    // types

    private:

        /** knows the state of this URL instance */
        sal_uInt32 m_eRequest;

        /** holds the event part of a job URL */
        ::rtl::OUString m_sEvent;

        /** holds the alias part of a job URL */
        ::rtl::OUString m_sAlias;

        /** holds the service part of a job URL */
        ::rtl::OUString m_sService;

        /** holds the event arguments */
        ::rtl::OUString m_sEventArgs;

        /** holds the alias arguments */
        ::rtl::OUString m_sAliasArgs;

        /** holds the service arguments */
        ::rtl::OUString m_sServiceArgs;

    //___________________________________
    // native interface

    public:

                 JobURL        ( const ::rtl::OUString& sURL         );
        sal_Bool isValid       (                                     ) const;
        sal_Bool getEvent      (       ::rtl::OUString& sEvent       ) const;
        sal_Bool getAlias      (       ::rtl::OUString& sAlias       ) const;
        sal_Bool getService    (       ::rtl::OUString& sService     ) const;
        sal_Bool getEventArgs  (       ::rtl::OUString& sEventArgs   ) const;
        sal_Bool getAliasArgs  (       ::rtl::OUString& sAliasArgs   ) const;
        sal_Bool getServiceArgs(       ::rtl::OUString& sServiceArgs ) const;

    //___________________________________
    // private helper

    private:

        static sal_Bool implst_split( const ::rtl::OUString& sPart           ,
                                      const sal_Char*        pPartIdentifier ,
                                            sal_Int32        nPartLength     ,
                                            ::rtl::OUString& rPartValue      ,
                                            ::rtl::OUString& rPartArguments  );

    //___________________________________
    // debug methods!

    #ifdef ENABLE_COMPONENT_SELF_CHECK

    public:
        static void impldbg_checkIt();

    private:
        static void impldbg_checkURL( const sal_Char*  pURL                 ,
                                            sal_uInt32 eExpectedPart        ,
                                      const sal_Char*  pExpectedEvent       ,
                                      const sal_Char*  pExpectedAlias       ,
                                      const sal_Char*  pExpectedService     ,
                                      const sal_Char*  pExpectedEventArgs   ,
                                      const sal_Char*  pExpectedAliasArgs   ,
                                      const sal_Char*  pExpectedServiceArgs );
        ::rtl::OUString impldbg_toString() const;

    #endif // ENABLE_COMPONENT_SELF_CHECK
};

} // namespace framework

#endif // __FRAMEWORK_JOBS_JOBURL_HXX_
<|endoftext|>


<commit_before>#ifndef regex_hh_INCLUDED
#define regex_hh_INCLUDED

#include "string.hh"
#include "exception.hh"
#include "utf8_iterator.hh"

#include <boost/regex.hpp>

namespace Kakoune
{

struct regex_error : runtime_error
{
    regex_error(StringView desc)
        : runtime_error{format("regex error: '{}'", desc)}
    {}
};

using RegexBase = boost::basic_regex<wchar_t, boost::c_regex_traits<wchar_t>>;

// Regex that keeps track of its string representation
class Regex : RegexBase
{
public:
    Regex() = default;

    explicit Regex(StringView re, flag_type flags = ECMAScript);
    bool empty() const { return m_str.empty(); }
    bool operator==(const Regex& other) const { return m_str == other.m_str; }
    bool operator!=(const Regex& other) const { return m_str != other.m_str; }

    const String& str() const { return m_str; }

    static constexpr const char* option_type_name = "regex";

private:
    String m_str;
};

template<typename It>
using RegexUtf8It = utf8::iterator<It, wchar_t, ssize_t>;

template<typename It>
using RegexIteratorBase = boost::regex_iterator<RegexUtf8It<It>, wchar_t,
                                                boost::c_regex_traits<wchar_t>>;

namespace RegexConstant = boost::regex_constants;

template<typename Iterator>
struct MatchResults : boost::match_results<RegexUtf8It<Iterator>>
{
    using ParentType = boost::match_results<RegexUtf8It<Iterator>>;
    struct SubMatch : std::pair<Iterator, Iterator>
    {
        SubMatch() = default;
        SubMatch(const boost::sub_match<RegexUtf8It<Iterator>>& m)
            : std::pair<Iterator, Iterator>{m.first.base(), m.second.base()},
              matched{m.matched}
        {}

        bool matched = false;
    };

    struct iterator : boost::match_results<RegexUtf8It<Iterator>>::iterator
    {
        using ParentType = typename boost::match_results<RegexUtf8It<Iterator>>::iterator;
        iterator(const ParentType& it) : ParentType(it) {}

        SubMatch operator*() const { return {ParentType::operator*()}; }
    };

    iterator begin() const { return {ParentType::begin()}; }
    iterator cbegin() const { return {ParentType::cbegin()}; }
    iterator end() const { return {ParentType::end()}; }
    iterator cend() const { return {ParentType::cend()}; }

    SubMatch operator[](size_t s) const { return {ParentType::operator[](s)}; }
};

template<typename Iterator>
struct RegexIterator : RegexIteratorBase<Iterator>
{
    using Utf8It = RegexUtf8It<Iterator>;
    using ValueType = MatchResults<Iterator>;

    RegexIterator() = default;
    RegexIterator(Iterator begin, Iterator end, const Regex& re,
                  RegexConstant::match_flag_type flags = RegexConstant::match_default)
        : RegexIteratorBase<Iterator>{Utf8It{begin, begin, end}, Utf8It{end, begin, end}, re, flags} {}

    const ValueType& operator*() const { return *reinterpret_cast<const ValueType*>(&RegexIteratorBase<Iterator>::operator*()); }
    const ValueType* operator->() const { return reinterpret_cast<const ValueType*>(RegexIteratorBase<Iterator>::operator->()); }
};

inline RegexConstant::match_flag_type match_flags(bool bol, bool eol, bool bow, bool eow)
{
    return (bol ? RegexConstant::match_default : RegexConstant::match_not_bol) |
           (eol ? RegexConstant::match_default : RegexConstant::match_not_eol) |
           (bow ? RegexConstant::match_default : RegexConstant::match_not_bow) |
           (eow ? RegexConstant::match_default : RegexConstant::match_not_eow);
}

template<typename It>
bool regex_match(It begin, It end, const Regex& re)
{
    using Utf8It = RegexUtf8It<It>;
    try
    {
        return boost::regex_match(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, re);
    }
    catch (std::runtime_error& err)
    {
        throw runtime_error{format("Regex matching error: {}", err.what())};
    }
}

template<typename It>
bool regex_match(It begin, It end, MatchResults<It>& res, const Regex& re)
{
    using Utf8It = RegexUtf8It<It>;
    try
    {
        return boost::regex_match(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, res, re);
    }
    catch (std::runtime_error& err)
    {
        throw runtime_error{format("Regex matching error: {}", err.what())};
    }
}

template<typename It>
bool regex_search(It begin, It end, const Regex& re,
                  RegexConstant::match_flag_type flags = RegexConstant::match_default)
{
    using Utf8It = RegexUtf8It<It>;
    try
    {
        return boost::regex_search(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, re, flags);
    }
    catch (std::runtime_error& err)
    {
        throw runtime_error{format("Regex searching error: {}", err.what())};
    }
}

template<typename It>
bool regex_search(It begin, It end, MatchResults<It>& res, const Regex& re,
                  RegexConstant::match_flag_type flags = RegexConstant::match_default)
{
    using Utf8It = RegexUtf8It<It>;
    try
    {
        return boost::regex_search(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, res, re, flags);
    }
    catch (std::runtime_error& err)
    {
        throw runtime_error{format("Regex searching error: {}", err.what())};
    }
}

String option_to_string(const Regex& re);
void option_from_string(StringView str, Regex& re);

}

#endif // regex_hh_INCLUDED
<commit_msg>Fix regex.hh compilation<commit_after>#ifndef regex_hh_INCLUDED
#define regex_hh_INCLUDED

#include "string.hh"
#include "exception.hh"
#include "utf8_iterator.hh"

#include <boost/regex.hpp>

namespace Kakoune
{

struct regex_error : runtime_error
{
    regex_error(StringView desc)
        : runtime_error{format("regex error: '{}'", desc)}
    {}
};

using RegexBase = boost::basic_regex<wchar_t, boost::c_regex_traits<wchar_t>>;

// Regex that keeps track of its string representation
class Regex : public RegexBase
{
public:
    Regex() = default;

    explicit Regex(StringView re, flag_type flags = ECMAScript);
    bool empty() const { return m_str.empty(); }
    bool operator==(const Regex& other) const { return m_str == other.m_str; }
    bool operator!=(const Regex& other) const { return m_str != other.m_str; }

    const String& str() const { return m_str; }

    static constexpr const char* option_type_name = "regex";

private:
    String m_str;
};

template<typename It>
using RegexUtf8It = utf8::iterator<It, wchar_t, ssize_t>;

template<typename It>
using RegexIteratorBase = boost::regex_iterator<RegexUtf8It<It>, wchar_t,
                                                boost::c_regex_traits<wchar_t>>;

namespace RegexConstant = boost::regex_constants;

template<typename Iterator>
struct MatchResults : boost::match_results<RegexUtf8It<Iterator>>
{
    using ParentType = boost::match_results<RegexUtf8It<Iterator>>;
    struct SubMatch : std::pair<Iterator, Iterator>
    {
        SubMatch() = default;
        SubMatch(const boost::sub_match<RegexUtf8It<Iterator>>& m)
            : std::pair<Iterator, Iterator>{m.first.base(), m.second.base()},
              matched{m.matched}
        {}

        bool matched = false;
    };

    struct iterator : boost::match_results<RegexUtf8It<Iterator>>::iterator
    {
        using ParentType = typename boost::match_results<RegexUtf8It<Iterator>>::iterator;
        iterator(const ParentType& it) : ParentType(it) {}

        SubMatch operator*() const { return {ParentType::operator*()}; }
    };

    iterator begin() const { return {ParentType::begin()}; }
    iterator cbegin() const { return {ParentType::cbegin()}; }
    iterator end() const { return {ParentType::end()}; }
    iterator cend() const { return {ParentType::cend()}; }

    SubMatch operator[](size_t s) const { return {ParentType::operator[](s)}; }
};

template<typename Iterator>
struct RegexIterator : RegexIteratorBase<Iterator>
{
    using Utf8It = RegexUtf8It<Iterator>;
    using ValueType = MatchResults<Iterator>;

    RegexIterator() = default;
    RegexIterator(Iterator begin, Iterator end, const Regex& re,
                  RegexConstant::match_flag_type flags = RegexConstant::match_default)
        : RegexIteratorBase<Iterator>{Utf8It{begin, begin, end}, Utf8It{end, begin, end}, re, flags} {}

    const ValueType& operator*() const { return *reinterpret_cast<const ValueType*>(&RegexIteratorBase<Iterator>::operator*()); }
    const ValueType* operator->() const { return reinterpret_cast<const ValueType*>(RegexIteratorBase<Iterator>::operator->()); }
};

inline RegexConstant::match_flag_type match_flags(bool bol, bool eol, bool bow, bool eow)
{
    return (bol ? RegexConstant::match_default : RegexConstant::match_not_bol) |
           (eol ? RegexConstant::match_default : RegexConstant::match_not_eol) |
           (bow ? RegexConstant::match_default : RegexConstant::match_not_bow) |
           (eow ? RegexConstant::match_default : RegexConstant::match_not_eow);
}

template<typename It>
bool regex_match(It begin, It end, const Regex& re)
{
    using Utf8It = RegexUtf8It<It>;
    try
    {
        return boost::regex_match(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, re);
    }
    catch (std::runtime_error& err)
    {
        throw runtime_error{format("Regex matching error: {}", err.what())};
    }
}

template<typename It>
bool regex_match(It begin, It end, MatchResults<It>& res, const Regex& re)
{
    using Utf8It = RegexUtf8It<It>;
    try
    {
        return boost::regex_match(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, res, re);
    }
    catch (std::runtime_error& err)
    {
        throw runtime_error{format("Regex matching error: {}", err.what())};
    }
}

template<typename It>
bool regex_search(It begin, It end, const Regex& re,
                  RegexConstant::match_flag_type flags = RegexConstant::match_default)
{
    using Utf8It = RegexUtf8It<It>;
    try
    {
        return boost::regex_search(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, re, flags);
    }
    catch (std::runtime_error& err)
    {
        throw runtime_error{format("Regex searching error: {}", err.what())};
    }
}

template<typename It>
bool regex_search(It begin, It end, MatchResults<It>& res, const Regex& re,
                  RegexConstant::match_flag_type flags = RegexConstant::match_default)
{
    using Utf8It = RegexUtf8It<It>;
    try
    {
        return boost::regex_search(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, res, re, flags);
    }
    catch (std::runtime_error& err)
    {
        throw runtime_error{format("Regex searching error: {}", err.what())};
    }
}

String option_to_string(const Regex& re);
void option_from_string(StringView str, Regex& re);

}

#endif // regex_hh_INCLUDED
<|endoftext|>


<commit_before>/*
 *
 * Author: Jeffrey Leung
 * Last edited: 2015-09-19
 *
 * This program contains implementations of a Room class, which is a template
 * to create a Labyrinth.
 *
 */

#include <iostream>
#include <stdexcept>

#include "../include/room_properties.hpp"
#include "../include/room.hpp"

// Parameterized constructor
// This constructor sets the necessary properties of a Room.
Room::Room( Inhabitant dark_thing,
            Item object,
            Direction exit,
            bool wall_north,
            bool wall_east,
            bool wall_south,
            bool wall_west )
{
  dark_thing_ = dark_thing;
  object_     = object;
  exit_       = exit;
  wall_north_ = wall_north;
  wall_east_  = wall_east;
  wall_south_ = wall_south;
  wall_west_  = wall_west;
}

// This method returns the current inhabitant of the Room.
Inhabitant Room::GetInhabitant() const
{
  return dark_thing_;
}

// This method changes the current inhabitant of the Room.
void Room::SetInhabitant( Inhabitant inh )
{
  dark_thing_ = inh;
  return;
}

// This method returns the current item in the Room.
Item Room::GetItem() const
{
  return object_;
}

// This method changes the current item in the Room.
void Room::SetItem( Item itm )
{
  object_ = itm;
  return;
}

// This method removes the Wall in the given direction so that the Room
// may be connected to another, or to set the exit.
// An exception is thrown if:
//   The Wall has already been removed (logic_error)
//   Direction d is null (i.e. Direction::kNone) (invalid_argument)
void Room::BreakWall( Direction d )
{
  switch( d )
  {
    case( Direction::kNone ):
      throw std::invalid_argument( "Error: BreakWall() was given an "\
        "invalid Direction (kNone). ");

    case( Direction::kNorth ):
      if( !wall_north_ )  // Wall already removed
      {
        throw std::logic_error( "Error: BreakWall() was given an "\
          "already-removed Wall." );
      }
      wall_north_ = false;
      break;

    case( Direction::kEast ):
      if( !wall_east_ )
      {
        throw std::logic_error( "Error: BreakWall() was given an "\
          "already-removed Wall." );
      }
      wall_east_ = false;
      break;

    case( Direction::kSouth ):
      if( !wall_south_ )
      {
        throw std::logic_error( "Error: BreakWall() was given an "\
          "already-removed Wall." );
      }
      wall_south_ = false;
      break;

    case( Direction::kWest ):
      if( !wall_west_ )
      {
        throw std::logic_error( "Error: BreakWall() was given an "\
          "already-removed Wall." );
      }
      wall_west_ = false;
      break;
  }
  return;
}

// This method returns:
//   RoomBorder::kExit if the direction has the exit,
//   RoomBorder::kRoom if the direction has another room, or
//   RoomBorder::kWall if the direction has a wall.
// An exception is thrown if:
//   Direction d is kNone (invalid_argument)
RoomBorder Room::DirectionCheck( Direction d ) const
{
  if( d == Direction::kNone )
  {
    throw std::invalid_argument( "Error: DirectionCheck() was given the "\
      "direction kNone.\n" ) ;
  }

  if( d == exit_ )
  {
    return RoomBorder::kExit;
  }

  else if( ( d == Direction::kNorth && !(wall_north_) ) ||
           ( d == Direction::kEast  && !(wall_east_)  ) ||
           ( d == Direction::kSouth && !(wall_south_) ) ||
           ( d == Direction::kWest  && !(wall_west_)  ) )
  {
    return RoomBorder::kRoom;
  }

  else
  {
    return RoomBorder::kWall;
  }
}
<commit_msg>Room: Adding newlines to exception messages.<commit_after>/*
 *
 * Author: Jeffrey Leung
 * Last edited: 2015-12-28
 *
 * This program contains implementations of a Room class, which is a template
 * to create a Labyrinth.
 *
 */

#include <iostream>
#include <stdexcept>

#include "../include/room_properties.hpp"
#include "../include/room.hpp"

// Parameterized constructor
// This constructor sets the necessary properties of a Room.
Room::Room( Inhabitant dark_thing,
            Item object,
            Direction exit,
            bool wall_north,
            bool wall_east,
            bool wall_south,
            bool wall_west )
{
  dark_thing_ = dark_thing;
  object_     = object;
  exit_       = exit;
  wall_north_ = wall_north;
  wall_east_  = wall_east;
  wall_south_ = wall_south;
  wall_west_  = wall_west;
}

// This method returns the current inhabitant of the Room.
Inhabitant Room::GetInhabitant() const
{
  return dark_thing_;
}

// This method changes the current inhabitant of the Room.
void Room::SetInhabitant( Inhabitant inh )
{
  dark_thing_ = inh;
  return;
}

// This method returns the current item in the Room.
Item Room::GetItem() const
{
  return object_;
}

// This method changes the current item in the Room.
void Room::SetItem( Item itm )
{
  object_ = itm;
  return;
}

// This method removes the Wall in the given direction so that the Room
// may be connected to another, or to set the exit.
// An exception is thrown if:
//   The Wall has already been removed (logic_error)
//   Direction d is null (i.e. Direction::kNone) (invalid_argument)
void Room::BreakWall( Direction d )
{
  switch( d )
  {
    case( Direction::kNone ):
      throw std::invalid_argument( "Error: BreakWall() was given an "\
        "invalid Direction (kNone).\n");

    case( Direction::kNorth ):
      if( !wall_north_ )  // Wall already removed
      {
        throw std::logic_error( "Error: BreakWall() was given an "\
          "already-removed Wall.\n" );
      }
      wall_north_ = false;
      break;

    case( Direction::kEast ):
      if( !wall_east_ )
      {
        throw std::logic_error( "Error: BreakWall() was given an "\
          "already-removed Wall.\n" );
      }
      wall_east_ = false;
      break;

    case( Direction::kSouth ):
      if( !wall_south_ )
      {
        throw std::logic_error( "Error: BreakWall() was given an "\
          "already-removed Wall.\n" );
      }
      wall_south_ = false;
      break;

    case( Direction::kWest ):
      if( !wall_west_ )
      {
        throw std::logic_error( "Error: BreakWall() was given an "\
          "already-removed Wall.\n" );
      }
      wall_west_ = false;
      break;
  }
  return;
}

// This method returns:
//   RoomBorder::kExit if the direction has the exit,
//   RoomBorder::kRoom if the direction has another room, or
//   RoomBorder::kWall if the direction has a wall.
// An exception is thrown if:
//   Direction d is kNone (invalid_argument)
RoomBorder Room::DirectionCheck( Direction d ) const
{
  if( d == Direction::kNone )
  {
    throw std::invalid_argument( "Error: DirectionCheck() was given the "\
      "direction kNone.\n" ) ;
  }

  if( d == exit_ )
  {
    return RoomBorder::kExit;
  }

  else if( ( d == Direction::kNorth && !(wall_north_) ) ||
           ( d == Direction::kEast  && !(wall_east_)  ) ||
           ( d == Direction::kSouth && !(wall_south_) ) ||
           ( d == Direction::kWest  && !(wall_west_)  ) )
  {
    return RoomBorder::kRoom;
  }

  else
  {
    return RoomBorder::kWall;
  }
}
<|endoftext|>


<commit_before>#include "lua/config.h"
#include "lua/state.h"
#include "rwte/logging.h"
#include "rwte/rwte.h"
#include "rwte/term.h"
#include "rwte/tty.h"
#include "rwte/window.h"

#include <memory>

// todo: mark [[noreturn]] funcs
// todo: std::starts_with/ends_with
// todo: std::span
// todo: std::bit_cast
// todo: std::shift_left/shift_right

// globals
Options options;
std::unique_ptr<Rwte> rwte;
lua_State* g_L = nullptr;

#define LOGGER() (logging::get("rwte"))

// default values to use if we don't have
// a default value in config
static const float DEFAULT_BLINK_RATE = 0.6;

Rwte::Rwte(std::shared_ptr<event::Bus> bus) :
    m_bus(std::move(bus)),
    m_refreshReg(m_bus->reg<event::Refresh, Rwte, &Rwte::onrefresh>(this)),
    m_lua(std::make_shared<lua::State>())
{
    m_lua->openlibs();

    m_child.set<Rwte, &Rwte::childcb>(this);
    m_flush.set<Rwte, &Rwte::flushcb>(this);
    m_blink.set<Rwte, &Rwte::blinkcb>(this);
}

Rwte::~Rwte()
{
    m_bus->unreg<event::Refresh>(m_refreshReg);
}

void Rwte::watch_child(pid_t pid)
{
    LOGGER()->debug("watching child {}", pid);
    m_child.start(pid);
}

void Rwte::refresh()
{
    // with xcb, we throttle drawing here
    if (options.throttledraw) {
        if (!m_flush.is_active())
            m_flush.start(1.0 / 60.0);
    } else {
        // for wayland, we let the window throttle
        if (auto window = m_window.lock())
            window->draw();
    }
}

void Rwte::start_blink()
{
    if (!m_blink.is_active()) {
        float rate = lua::config::get_float(
                "blink_rate", DEFAULT_BLINK_RATE);

        m_blink.start(rate, rate);
    } else {
        // reset the timer if it's already active
        // (so we don't blink until idle)
        m_blink.stop();
        m_blink.start();
    }
}

void Rwte::stop_blink()
{
    if (m_blink.is_active())
        m_blink.stop();
}

void Rwte::onrefresh(const event::Refresh& evt)
{
    refresh();
}

void Rwte::childcb(ev::child& w, int)
{
    if (WIFEXITED(w.rstatus) && WEXITSTATUS(w.rstatus))
        LOGGER()->warn("child exited with status {}", WEXITSTATUS(w.rstatus));
    else if (WIFSIGNALED(w.rstatus))
        LOGGER()->info("child terminated to to signal {}", WTERMSIG(w.rstatus));
    w.loop.break_loop(ev::ALL);
}

void Rwte::flushcb(ev::timer&, int)
{
    if (auto window = m_window.lock())
        window->draw();
}

void Rwte::blinkcb(ev::timer&, int)
{
    if (auto term = m_term.lock())
        term->blink();
}
<commit_msg>Another constexpr, added more todos.<commit_after>#include "lua/config.h"
#include "lua/state.h"
#include "rwte/logging.h"
#include "rwte/rwte.h"
#include "rwte/term.h"
#include "rwte/tty.h"
#include "rwte/window.h"

#include <memory>

// todo: mark [[noreturn]] funcs
// todo: std::starts_with/ends_with
// todo: std::span
// todo: std::bit_cast
// todo: std::shift_left/shift_right
// todo: more std::string_view
// todo: memset/memcpy/memmove
// todo: std::exit and EXIT_x
// todo: nest impl classes
// todo: use override keyword
// todo: look for initializer in if or switch
// todo: bench codecvt vs utf8

// globals
Options options;
std::unique_ptr<Rwte> rwte;
lua_State* g_L = nullptr;

#define LOGGER() (logging::get("rwte"))

// default values to use if we don't have
// a default value in config
constexpr float DEFAULT_BLINK_RATE = 0.6;

Rwte::Rwte(std::shared_ptr<event::Bus> bus) :
    m_bus(std::move(bus)),
    m_refreshReg(m_bus->reg<event::Refresh, Rwte, &Rwte::onrefresh>(this)),
    m_lua(std::make_shared<lua::State>())
{
    m_lua->openlibs();

    m_child.set<Rwte, &Rwte::childcb>(this);
    m_flush.set<Rwte, &Rwte::flushcb>(this);
    m_blink.set<Rwte, &Rwte::blinkcb>(this);
}

Rwte::~Rwte()
{
    m_bus->unreg<event::Refresh>(m_refreshReg);
}

void Rwte::watch_child(pid_t pid)
{
    LOGGER()->debug("watching child {}", pid);
    m_child.start(pid);
}

void Rwte::refresh()
{
    // with xcb, we throttle drawing here
    if (options.throttledraw) {
        if (!m_flush.is_active())
            m_flush.start(1.0 / 60.0);
    } else {
        // for wayland, we let the window throttle
        if (auto window = m_window.lock())
            window->draw();
    }
}

void Rwte::start_blink()
{
    if (!m_blink.is_active()) {
        float rate = lua::config::get_float(
                "blink_rate", DEFAULT_BLINK_RATE);

        m_blink.start(rate, rate);
    } else {
        // reset the timer if it's already active
        // (so we don't blink until idle)
        m_blink.stop();
        m_blink.start();
    }
}

void Rwte::stop_blink()
{
    if (m_blink.is_active())
        m_blink.stop();
}

void Rwte::onrefresh(const event::Refresh& evt)
{
    refresh();
}

void Rwte::childcb(ev::child& w, int)
{
    if (WIFEXITED(w.rstatus) && WEXITSTATUS(w.rstatus))
        LOGGER()->warn("child exited with status {}", WEXITSTATUS(w.rstatus));
    else if (WIFSIGNALED(w.rstatus))
        LOGGER()->info("child terminated to to signal {}", WTERMSIG(w.rstatus));
    w.loop.break_loop(ev::ALL);
}

void Rwte::flushcb(ev::timer&, int)
{
    if (auto window = m_window.lock())
        window->draw();
}

void Rwte::blinkcb(ev::timer&, int)
{
    if (auto term = m_term.lock())
        term->blink();
}
<|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 <memory>
#include <boost/thread.hpp>

#include <SurgSim/Blocks/BasicSceneElement.h>
#include <SurgSim/Blocks/TransferDeformableStateToVerticesBehavior.h>
#include <SurgSim/Framework/Behavior.h>
#include <SurgSim/Framework/BehaviorManager.h>
#include <SurgSim/Framework/Runtime.h>
#include <SurgSim/Framework/Scene.h>
#include <SurgSim/Framework/SceneElement.h>
#include <SurgSim/Graphics/OsgCamera.h>
#include <SurgSim/Graphics/OsgManager.h>
#include <SurgSim/Graphics/OsgView.h>
#include <SurgSim/Graphics/OsgViewElement.h>
#include <SurgSim/Graphics/OsgPointCloudRepresentation.h>
#include <SurgSim/Physics/PhysicsManager.h>
#include <SurgSim/Physics/Fem3DRepresentation.h>
#include <SurgSim/Physics/FemElement3DTetrahedron.h>
#include <SurgSim/Math/Vector.h>
#include <SurgSim/Math/Quaternion.h>
#include <SurgSim/Math/RigidTransform.h>

using SurgSim::Blocks::BasicSceneElement;
using SurgSim::Blocks::TransferDeformableStateToVerticesBehavior;
using SurgSim::Framework::Logger;
using SurgSim::Framework::SceneElement;
using SurgSim::Graphics::OsgPointCloudRepresentation;
using SurgSim::Physics::DeformableRepresentationState;
using SurgSim::Physics::Fem3DRepresentation;
using SurgSim::Physics::FemElement3DTetrahedron;
using SurgSim::Physics::PhysicsManager;
using SurgSim::Math::Vector3d;
using SurgSim::Math::Vector4f;

///\file Example of how to put together a very simple demo of Fem3D

namespace
{
	// Cube nodes
	//       2*-----------*3
	//       /           /|
	//    6*-----------*7 |      ^ y
	//     |           |  |      |
	//     |  0        |  *1     *->x
	//     |           | /      /
	//    4*-----------*5       z
	std::array<SurgSim::Math::Vector3d, 8> cubeNodes =
	{{
		Vector3d(-0.5,-0.5,-0.5), Vector3d( 0.5,-0.5,-0.5),
		Vector3d(-0.5, 0.5,-0.5), Vector3d( 0.5, 0.5,-0.5),
		Vector3d(-0.5,-0.5, 0.5), Vector3d( 0.5,-0.5, 0.5),
		Vector3d(-0.5, 0.5, 0.5), Vector3d( 0.5, 0.5, 0.5)
	}};

	// Cube decomposition into 5 tetrahedrons
	// https://www.math.ucdavis.edu/~deloera/CURRENT_INTERESTS/cube.html
	const unsigned int numTetrahedrons = 5;
	std::array< std::array<unsigned int, 4>, numTetrahedrons> tetrahedrons =
	{{
		{{4, 7, 1, 2}}, // CCW (47)cross(41) . (42) > 0
		{{4, 1, 7, 5}}, // CCW (41)cross(47) . (45) > 0
		{{4, 2, 1, 0}}, // CCW (42)cross(41) . (40) > 0
		{{4, 7, 2, 6}}, // CCW (47)cross(42) . (46) > 0
		{{1, 2, 7, 3}}  // CCW (12)cross(17) . (13) > 0
	}};

	// Boundary conditions (node indices)
	const unsigned int numBoundaryConditionsNodeIdx = 4;
	const std::array<unsigned int, numBoundaryConditionsNodeIdx> boundaryConditionsNodeIdx =
	{{
		0, 1, 2, 3
	}};

	void loadCubeModelFem3D(std::shared_ptr<Fem3DRepresentation> *physicsRepresentation)
	{
		std::shared_ptr<DeformableRepresentationState> restState = std::make_shared<DeformableRepresentationState>();
		restState->setNumDof((*physicsRepresentation)->getNumDofPerNode(), 8);
		Vector& x = restState->getPositions();

		// Sets the initial state (node positions and boundary conditions)
		for (int nodeId = 0; nodeId < 8; nodeId++)
		{
			SurgSim::Math::getSubVector(x, nodeId, 3) =  cubeNodes[nodeId];
		}
		for (unsigned int boundaryConditionId = 0;
			boundaryConditionId < numBoundaryConditionsNodeIdx;
			boundaryConditionId++)
		{
			// The boundary conditions in the state are the dof indices to be fixed
			restState->addBoundaryCondition(boundaryConditionsNodeIdx[boundaryConditionId] * 3 + 0);
			restState->addBoundaryCondition(boundaryConditionsNodeIdx[boundaryConditionId] * 3 + 1);
			restState->addBoundaryCondition(boundaryConditionsNodeIdx[boundaryConditionId] * 3 + 2);
		}
		(*physicsRepresentation)->setInitialState(restState);

		// Adds all the FemElements
		for (unsigned int tetId = 0; tetId < numTetrahedrons; tetId++)
		{
			std::shared_ptr<FemElement3DTetrahedron> tet = nullptr;
			tet = std::make_shared<FemElement3DTetrahedron>(tetrahedrons[tetId], *restState);
			tet->setMassDensity(8000.0);
			tet->setPoissonRatio(0.45);
			tet->setYoungModulus(1e6);
			(*physicsRepresentation)->addFemElement(tet);
		}

		// Calls Initialize() after adding the FemElements and setting the initial state
		(*physicsRepresentation)->Initialize();
	}

};

std::shared_ptr<SurgSim::Graphics::ViewElement> createView(const std::string& name, int x, int y, int width, int height)
{
	using SurgSim::Graphics::OsgViewElement;

	std::shared_ptr<OsgViewElement> viewElement = std::make_shared<OsgViewElement>(name);
	viewElement->getView()->setPosition(x, y);
	viewElement->getView()->setDimensions(width, height);

	return viewElement;
}

std::shared_ptr<SceneElement> createFem3D(const std::string& name,
	const std::vector<SurgSim::Math::RigidTransform3d> gfxPoses,
	SurgSim::Math::Vector4d color, SurgSim::Math::IntegrationScheme integrationScheme)
{
	std::shared_ptr<Fem3DRepresentation> physicsRepresentation =
		std::make_shared<Fem3DRepresentation>(name + " Physics");

	// In this example, the physics representations are not transformed,
	// only the graphics one will apply a transform
	loadCubeModelFem3D(&physicsRepresentation);

	physicsRepresentation->setIntegrationScheme(integrationScheme);
	physicsRepresentation->setRayleighDampingMass(5e-2);
	physicsRepresentation->setRayleighDampingStiffness(5e-3);

	std::shared_ptr<SceneElement> massSpringElement = std::make_shared<BasicSceneElement>(name);
	massSpringElement->addComponent(physicsRepresentation);

	unsigned int gfxObjectId = 0;
	for (auto gfxPose = std::begin(gfxPoses); gfxPose != std::end(gfxPoses); gfxPose++)
	{
		std::stringstream ss;
		ss << name + " Graphics object " << gfxObjectId;
		std::shared_ptr<OsgPointCloudRepresentation<void>> graphicsRepresentation =
			std::make_shared<OsgPointCloudRepresentation<void>>(ss.str());
		std::shared_ptr<SurgSim::DataStructures::Vertices<void>> vertices;
		vertices = std::make_shared<SurgSim::DataStructures::Vertices<void>>();

		graphicsRepresentation->setInitialPose(*gfxPose);

		graphicsRepresentation->setVertices(vertices);
		graphicsRepresentation->setColor(color);
		graphicsRepresentation->setPointSize(3.0f);
		graphicsRepresentation->setVisible(true);

		massSpringElement->addComponent(graphicsRepresentation);
		ss.clear();
		ss << "Physics to Graphics ("<< gfxObjectId <<") deformable points";
		massSpringElement->addComponent(std::make_shared<TransferDeformableStateToVerticesBehavior<void>>
			(ss.str(),
			physicsRepresentation->getFinalState(),
			graphicsRepresentation->getVertices()));

		gfxObjectId++;
	}

	return massSpringElement;

}

int main(int argc, char* argv[])
{
	using SurgSim::Math::makeRigidTransform;
	using SurgSim::Math::Vector4d;

	std::shared_ptr<SurgSim::Graphics::OsgManager> graphicsManager = std::make_shared<SurgSim::Graphics::OsgManager>();
	std::shared_ptr<PhysicsManager> physicsManager = std::make_shared<PhysicsManager>();
	std::shared_ptr<SurgSim::Framework::BehaviorManager> behaviorManager =
		std::make_shared<SurgSim::Framework::BehaviorManager>();
	std::shared_ptr<SurgSim::Framework::Runtime> runtime(new SurgSim::Framework::Runtime());

	runtime->addManager(physicsManager);
	runtime->addManager(graphicsManager);
	runtime->addManager(behaviorManager);

	std::shared_ptr<SurgSim::Framework::Scene> scene(new SurgSim::Framework::Scene());

	SurgSim::Math::Quaterniond qIdentity = SurgSim::Math::Quaterniond::Identity();
	SurgSim::Math::Vector3d translate(0,0,-3);

	{
		std::vector<SurgSim::Math::RigidTransform3d> gfxPoses;

		gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d(-3.0, 0.5, 0.0)));
		gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d( 3.0, 0.5, 0.0)));
		scene->addSceneElement(createFem3D("Euler Explicit",
			gfxPoses, Vector4d(1, 0, 0, 1),
			SurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER));

		gfxPoses.clear();
		gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d(-1.0, 0.5, 0.0)));
		gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d( 3.0, 0.5, 0.0)));
		scene->addSceneElement(createFem3D("Modified Euler Explicit",
			gfxPoses, Vector4d(0, 1, 0, 1),
			SurgSim::Math::INTEGRATIONSCHEME_MODIFIED_EXPLICIT_EULER));

		gfxPoses.clear();
		gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d( 1.0, 0.5, 0.0)));
		gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d( 3.0, 0.5, 0.0)));
		scene->addSceneElement(createFem3D("Fem 3D Euler Implicit",
			gfxPoses, Vector4d(0, 0, 1, 1),
			SurgSim::Math::INTEGRATIONSCHEME_IMPLICIT_EULER));
	}

	scene->addSceneElement(createView("view1", 0, 0, 1023, 768));

	graphicsManager->getDefaultCamera()->setInitialPose(
		SurgSim::Math::makeRigidTransform(SurgSim::Math::Quaterniond::Identity(), Vector3d(0.0, 0.5, 5.0)));

	runtime->setScene(scene);

	runtime->execute();

	return 0;
}
<commit_msg>Fix broken ExampleFem3D after merge with master (OsgPointCloud handles its vertices)<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 <memory>
#include <boost/thread.hpp>

#include <SurgSim/Blocks/BasicSceneElement.h>
#include <SurgSim/Blocks/TransferDeformableStateToVerticesBehavior.h>
#include <SurgSim/Framework/Behavior.h>
#include <SurgSim/Framework/BehaviorManager.h>
#include <SurgSim/Framework/Runtime.h>
#include <SurgSim/Framework/Scene.h>
#include <SurgSim/Framework/SceneElement.h>
#include <SurgSim/Graphics/OsgCamera.h>
#include <SurgSim/Graphics/OsgManager.h>
#include <SurgSim/Graphics/OsgView.h>
#include <SurgSim/Graphics/OsgViewElement.h>
#include <SurgSim/Graphics/OsgPointCloudRepresentation.h>
#include <SurgSim/Physics/PhysicsManager.h>
#include <SurgSim/Physics/Fem3DRepresentation.h>
#include <SurgSim/Physics/FemElement3DTetrahedron.h>
#include <SurgSim/Math/Vector.h>
#include <SurgSim/Math/Quaternion.h>
#include <SurgSim/Math/RigidTransform.h>

using SurgSim::Blocks::BasicSceneElement;
using SurgSim::Blocks::TransferDeformableStateToVerticesBehavior;
using SurgSim::Framework::Logger;
using SurgSim::Framework::SceneElement;
using SurgSim::Graphics::OsgPointCloudRepresentation;
using SurgSim::Physics::DeformableRepresentationState;
using SurgSim::Physics::Fem3DRepresentation;
using SurgSim::Physics::FemElement3DTetrahedron;
using SurgSim::Physics::PhysicsManager;
using SurgSim::Math::Vector3d;
using SurgSim::Math::Vector4f;

///\file Example of how to put together a very simple demo of Fem3D

namespace
{
	// Cube nodes
	//       2*-----------*3
	//       /           /|
	//    6*-----------*7 |      ^ y
	//     |           |  |      |
	//     |  0        |  *1     *->x
	//     |           | /      /
	//    4*-----------*5       z
	std::array<SurgSim::Math::Vector3d, 8> cubeNodes =
	{{
		Vector3d(-0.5,-0.5,-0.5), Vector3d( 0.5,-0.5,-0.5),
		Vector3d(-0.5, 0.5,-0.5), Vector3d( 0.5, 0.5,-0.5),
		Vector3d(-0.5,-0.5, 0.5), Vector3d( 0.5,-0.5, 0.5),
		Vector3d(-0.5, 0.5, 0.5), Vector3d( 0.5, 0.5, 0.5)
	}};

	// Cube decomposition into 5 tetrahedrons
	// https://www.math.ucdavis.edu/~deloera/CURRENT_INTERESTS/cube.html
	const unsigned int numTetrahedrons = 5;
	std::array< std::array<unsigned int, 4>, numTetrahedrons> tetrahedrons =
	{{
		{{4, 7, 1, 2}}, // CCW (47)cross(41) . (42) > 0
		{{4, 1, 7, 5}}, // CCW (41)cross(47) . (45) > 0
		{{4, 2, 1, 0}}, // CCW (42)cross(41) . (40) > 0
		{{4, 7, 2, 6}}, // CCW (47)cross(42) . (46) > 0
		{{1, 2, 7, 3}}  // CCW (12)cross(17) . (13) > 0
	}};

	// Boundary conditions (node indices)
	const unsigned int numBoundaryConditionsNodeIdx = 4;
	const std::array<unsigned int, numBoundaryConditionsNodeIdx> boundaryConditionsNodeIdx =
	{{
		0, 1, 2, 3
	}};

	void loadCubeModelFem3D(std::shared_ptr<Fem3DRepresentation> *physicsRepresentation)
	{
		std::shared_ptr<DeformableRepresentationState> restState = std::make_shared<DeformableRepresentationState>();
		restState->setNumDof((*physicsRepresentation)->getNumDofPerNode(), 8);
		Vector& x = restState->getPositions();

		// Sets the initial state (node positions and boundary conditions)
		for (int nodeId = 0; nodeId < 8; nodeId++)
		{
			SurgSim::Math::getSubVector(x, nodeId, 3) =  cubeNodes[nodeId];
		}
		for (unsigned int boundaryConditionId = 0;
			boundaryConditionId < numBoundaryConditionsNodeIdx;
			boundaryConditionId++)
		{
			// The boundary conditions in the state are the dof indices to be fixed
			restState->addBoundaryCondition(boundaryConditionsNodeIdx[boundaryConditionId] * 3 + 0);
			restState->addBoundaryCondition(boundaryConditionsNodeIdx[boundaryConditionId] * 3 + 1);
			restState->addBoundaryCondition(boundaryConditionsNodeIdx[boundaryConditionId] * 3 + 2);
		}
		(*physicsRepresentation)->setInitialState(restState);

		// Adds all the FemElements
		for (unsigned int tetId = 0; tetId < numTetrahedrons; tetId++)
		{
			std::shared_ptr<FemElement3DTetrahedron> tet = nullptr;
			tet = std::make_shared<FemElement3DTetrahedron>(tetrahedrons[tetId], *restState);
			tet->setMassDensity(8000.0);
			tet->setPoissonRatio(0.45);
			tet->setYoungModulus(1e6);
			(*physicsRepresentation)->addFemElement(tet);
		}

		// Calls Initialize() after adding the FemElements and setting the initial state
		(*physicsRepresentation)->Initialize();
	}

};

std::shared_ptr<SurgSim::Graphics::ViewElement> createView(const std::string& name, int x, int y, int width, int height)
{
	using SurgSim::Graphics::OsgViewElement;

	std::shared_ptr<OsgViewElement> viewElement = std::make_shared<OsgViewElement>(name);
	viewElement->getView()->setPosition(x, y);
	viewElement->getView()->setDimensions(width, height);

	return viewElement;
}

std::shared_ptr<SceneElement> createFem3D(const std::string& name,
	const std::vector<SurgSim::Math::RigidTransform3d> gfxPoses,
	SurgSim::Math::Vector4d color, SurgSim::Math::IntegrationScheme integrationScheme)
{
	std::shared_ptr<Fem3DRepresentation> physicsRepresentation =
		std::make_shared<Fem3DRepresentation>(name + " Physics");

	// In this example, the physics representations are not transformed,
	// only the graphics one will apply a transform
	loadCubeModelFem3D(&physicsRepresentation);

	physicsRepresentation->setIntegrationScheme(integrationScheme);
	physicsRepresentation->setRayleighDampingMass(5e-2);
	physicsRepresentation->setRayleighDampingStiffness(5e-3);

	std::shared_ptr<SceneElement> massSpringElement = std::make_shared<BasicSceneElement>(name);
	massSpringElement->addComponent(physicsRepresentation);

	unsigned int gfxObjectId = 0;
	for (auto gfxPose = std::begin(gfxPoses); gfxPose != std::end(gfxPoses); gfxPose++)
	{
		std::stringstream ss;
		ss << name + " Graphics object " << gfxObjectId;
		std::shared_ptr<OsgPointCloudRepresentation<void>> graphicsRepresentation =
			std::make_shared<OsgPointCloudRepresentation<void>>(ss.str());

		graphicsRepresentation->setInitialPose(*gfxPose);
		graphicsRepresentation->setColor(color);
		graphicsRepresentation->setPointSize(3.0f);
		graphicsRepresentation->setVisible(true);

		massSpringElement->addComponent(graphicsRepresentation);
		ss.clear();
		ss << "Physics to Graphics ("<< gfxObjectId <<") deformable points";
		massSpringElement->addComponent(std::make_shared<TransferDeformableStateToVerticesBehavior<void>>
			(ss.str(),
			physicsRepresentation->getFinalState(),
			graphicsRepresentation->getVertices()));

		gfxObjectId++;
	}

	return massSpringElement;

}

int main(int argc, char* argv[])
{
	using SurgSim::Math::makeRigidTransform;
	using SurgSim::Math::Vector4d;

	std::shared_ptr<SurgSim::Graphics::OsgManager> graphicsManager = std::make_shared<SurgSim::Graphics::OsgManager>();
	std::shared_ptr<PhysicsManager> physicsManager = std::make_shared<PhysicsManager>();
	std::shared_ptr<SurgSim::Framework::BehaviorManager> behaviorManager =
		std::make_shared<SurgSim::Framework::BehaviorManager>();
	std::shared_ptr<SurgSim::Framework::Runtime> runtime(new SurgSim::Framework::Runtime());

	runtime->addManager(physicsManager);
	runtime->addManager(graphicsManager);
	runtime->addManager(behaviorManager);

	std::shared_ptr<SurgSim::Framework::Scene> scene(new SurgSim::Framework::Scene());

	SurgSim::Math::Quaterniond qIdentity = SurgSim::Math::Quaterniond::Identity();
	SurgSim::Math::Vector3d translate(0,0,-3);

	{
		std::vector<SurgSim::Math::RigidTransform3d> gfxPoses;

		gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d(-3.0, 0.5, 0.0)));
		gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d( 3.0, 0.5, 0.0)));
		scene->addSceneElement(createFem3D("Euler Explicit",
			gfxPoses, Vector4d(1, 0, 0, 1),
			SurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER));

		gfxPoses.clear();
		gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d(-1.0, 0.5, 0.0)));
		gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d( 3.0, 0.5, 0.0)));
		scene->addSceneElement(createFem3D("Modified Euler Explicit",
			gfxPoses, Vector4d(0, 1, 0, 1),
			SurgSim::Math::INTEGRATIONSCHEME_MODIFIED_EXPLICIT_EULER));

		gfxPoses.clear();
		gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d( 1.0, 0.5, 0.0)));
		gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d( 3.0, 0.5, 0.0)));
		scene->addSceneElement(createFem3D("Fem 3D Euler Implicit",
			gfxPoses, Vector4d(0, 0, 1, 1),
			SurgSim::Math::INTEGRATIONSCHEME_IMPLICIT_EULER));
	}

	scene->addSceneElement(createView("view1", 0, 0, 1023, 768));

	graphicsManager->getDefaultCamera()->setInitialPose(
		SurgSim::Math::makeRigidTransform(SurgSim::Math::Quaterniond::Identity(), Vector3d(0.0, 0.5, 5.0)));

	runtime->setScene(scene);

	runtime->execute();

	return 0;
}
<|endoftext|>