<commit_before>// merge_sort.cpp
//
// Author: Daniel Clark, 2015

// Headers
#include <iostream>

// Namespace
using namespace std;

// Print the array to screen
void print_array(int *arr, int size) {
    // For each element in the array, print to cout
    for (int idx = 0; idx < size; idx++) {
        cout << arr[idx];
        if (idx != size-1) {
            cout << ", ";
        }
        else {
            cout << '\n';
        }
    }
}

// Merge sort function
void merge_sort(int *arr, int size) {

}

// Main function
int main() {

    // Declare/init variables
    int unsorted_array[] = { 5, 4, 1, 8, 7, 2, 6, 3, 4, 1 };

    // Get length of array
    int array_size = sizeof(unsorted_array) / sizeof(*unsorted_array);

    // Print unsorted values
    cout << "Unsorted array elements:\n";
    print_array(unsorted_array, array_size);

    //

    return 0;
}
<commit_msg>Updated merge sort script with recursive top-down algorithm<commit_after>// merge_sort.cpp
//
// Author: Daniel Clark, 2015

// Headers
#include <iostream>

// Namespace
using namespace std;

// Print the array to screen
void print_array(int * arr, int size) {
    cout << "{";
    // For each element in the array, print to cout
    for (int idx = 0; idx < size; idx++) {
        cout << arr[idx];
        if (idx != size-1) {
            cout << ", ";
        }
        else {
            cout << "}\n";
        }
    }
}

// Function to do the sorting and merging of arrays
void merge(int * arr, const int low, const int mid, const int high)
{
    /*
    Function to actually merge and sort the array elements

    Parameters
    ----------
    arr : integer ptr
        pointer to the head of an integer array to sort
    low : constant integer
        the low index of the array to start evaluation at
    mid : constant integer
        the mid point (mid+1 for odd lengths)
    high : constant integer
        the high index of the array to end evaluation at
    */

    // Init variables
    int * work_arr = new int[high+1-low];
    int work_idx = 0;
    int fhalf_idx = low;
    int lhalf_idx = mid+1;

    // Merges the two array's into work_arr[]
    // until we've gone through one of them
    while((fhalf_idx <= mid) && (lhalf_idx <= high))
    {
        // If first half idx val is <= last half idx val
        if(arr[fhalf_idx] <= arr[lhalf_idx])
        {
            // Put first half idx val in worker array
            work_arr[work_idx] = arr[fhalf_idx];
            // Increment first half idx
            fhalf_idx++;
        }
        // Otherwise, last half idx val is > first half idx val
        else
        {
            // Put last half idx val in worker array
            work_arr[work_idx] = arr[lhalf_idx];
            // Icrement last half idx
            lhalf_idx++;
        }
        // Index worker array idx
        work_idx++;
    }

    // If first half idx made it past mid, then first half is sorted
    if(fhalf_idx > mid)
    {
        for(int k = lhalf_idx; k <= high; k++)
        {
            work_arr[work_idx] = arr[k];
            work_idx++;
        }
    }
    else
    {
        for(int k = fhalf_idx; k <= mid; k++)
        {
            work_arr[work_idx] = arr[k];
            work_idx++;
        }
    }

    // Prints into the original array
    for(int k=0; k <= high-low; k++)
    {
        arr[k+low] = work_arr[k];
    }
    delete[] work_arr;
}

// Merge sort function
void merge_sort(int * arr, const int low, const int high)
{
    /*
    Function to perform top-down merge sort

    Parameters
    ----------
    arr : integer ptr
        pointer to integer (array)
    low : constant int
        the low (first) index of the array
    high : constant int
        the high (last) index of the array

    Returns
    -------

    */

    // Declare mid point index integer
    int mid;
    int arr_size = (high-low)+1;

    // If there is more than one element in array, split it recursively
    if( low < high ) {
        cout << "Splitting array: ";
        print_array(arr, arr_size);

        // Get halfway point
        mid = (low+high)/2;

        // Split left half recursively until only two elements
        cout << "Splitting left side\n";
        merge_sort(arr, low, mid);

        // Split right half - first time with only two elements
        cout << "Splitting right side\n";
        merge_sort(arr, mid+1, high);

        // Merge the array
        cout << "Merging/sorting array: ";
        print_array(arr, arr_size);
        merge(arr, low, mid, high);

        // Print full array so far...
        cout << "Array now: ";
        print_array(arr, 10);
    }
}

// Main function
int main()
{
    // Declare/init variawork_arrles
    int input_arr[] = {5, 4, 1, 8, 7, 2, 6, 3, 4, 1};

    // Get length of array - size (work_arrytes) of variable / size of element
    int array_size = sizeof(input_arr) / sizeof(*input_arr);

    // Print unsorted values
    cout << "Unsorted array elements:\n";
    print_array(input_arr, array_size);

    // Merge-sort the array
    merge_sort(input_arr, 0, (array_size-1) );

    // Print sorted values
    cout << "Sorted array elements:\n";
    print_array(input_arr, array_size);

    return 0;
}
<|endoftext|>


<commit_before>#pragma once

#include <deque>
#include <memory>
#include <iostream>
#include <map>
#include <utility>

template <typename T>
class MessageBusProxy;

namespace {
	using Cursor = long unsigned int;

}

template <typename MessageType>
class MessageBus {
	public:

		MessageBus()=default;

		void push(const MessageType& message);

		template<typename ResponseType>
		const std::vector<ResponseType>&& request(const MessageType& message);

		static MessageBus<MessageType>* getBus();

		MessageType* next(MessageBusProxy<MessageType>* proxy);

	private:
		using MessageQueue = std::deque<MessageType>;
		friend class MessageBusProxy<MessageType>;

		void registerProxy(MessageBusProxy<MessageType>* proxy);
		void unregisterProxy(MessageBusProxy<MessageType>* proxy);

		MessageQueue m_messages;
		std::map<MessageBusProxy<MessageType>*, typename MessageQueue::iterator> m_proxys;

		static std::unique_ptr<MessageBus<MessageType>> m_bus;
};

#include "messagebusqueue.hpp"
#include "messagebusproxy.hpp"

template <typename MessageType>
void MessageBus<MessageType>::push(const MessageType& message)
{
	if (m_proxys.size() == 0)
		return;
	MessageBusQueue::instance()->push<MessageType>();
	m_messages.push_back(message);
}

template <typename MessageType>
MessageBus<MessageType>* MessageBus<MessageType>::getBus()
{
	if (m_bus == nullptr)
	{
		std::cout << "bus expired"<< std::endl;
		m_bus.reset(new MessageBus<MessageType>());
	}
	return m_bus.get();
}

template <typename MessageType>
void MessageBus<MessageType>::registerProxy(MessageBusProxy<MessageType>* proxy) {
	auto cursor = m_messages.begin();
	if (m_messages.size() > 0)
		std::advance(cursor, m_messages.size()-1);
	m_proxys.emplace(proxy, cursor);
}

template <typename MessageType>
void MessageBus<MessageType>::unregisterProxy(MessageBusProxy<MessageType>* proxy) {
	auto _search = m_proxys.find(proxy);
	if (_search == m_proxys.end())
		return;
	m_proxys.erase(_search);

	if (m_proxys.size() == 0)
		delete m_bus.release();
}

template <typename MessageType>
MessageType* MessageBus<MessageType>::next(MessageBusProxy<MessageType>* proxy) {
	// TODO : implement next function
	auto& iterator = m_proxys.at(proxy);
	if (iterator == m_messages.end())
		return nullptr;
	return &*(++iterator);
}

template <typename MessageType>
std::unique_ptr<MessageBus<MessageType>> MessageBus<MessageType>::m_bus = nullptr;

template <typename MessageType>
void SendMessage(const MessageType& message) {
	MessageBus<MessageType>::getBus()->push(message);
}

template <typename MessageType, typename ResponseType>
const std::vector<ResponseType>&& RequestMessage(const MessageType& message)
{
	MessageBus<MessageType>::getBus()->request(message);
}

template <typename MessageType, typename ResponseType>
const ResponseType& RequestUnique(const MessageType& message)
{
	auto& response = RequestMessage<MessageType, ResponseType>(message);
	if (response.size() != 1) throw std::runtime_error("More than 1 response");
	return response[0];
}

<commit_msg>Fix iterator incrementation.<commit_after>#pragma once

#include <deque>
#include <memory>
#include <iostream>
#include <map>
#include <utility>

template <typename T>
class MessageBusProxy;

namespace {
	using Cursor = long unsigned int;

}

template <typename MessageType>
class MessageBus {
	public:

		MessageBus()=default;

		void push(const MessageType& message);

		template<typename ResponseType>
		const std::vector<ResponseType>&& request(const MessageType& message);

		static MessageBus<MessageType>* getBus();

		MessageType* next(MessageBusProxy<MessageType>* proxy);

	private:
		using MessageQueue = std::deque<MessageType>;
		friend class MessageBusProxy<MessageType>;

		void registerProxy(MessageBusProxy<MessageType>* proxy);
		void unregisterProxy(MessageBusProxy<MessageType>* proxy);

		MessageQueue m_messages;
		std::map<MessageBusProxy<MessageType>*, typename MessageQueue::iterator> m_proxys;

		static std::unique_ptr<MessageBus<MessageType>> m_bus;
};

#include "messagebusqueue.hpp"
#include "messagebusproxy.hpp"

template <typename MessageType>
void MessageBus<MessageType>::push(const MessageType& message)
{
	if (m_proxys.size() == 0)
		return;
	MessageBusQueue::instance()->push<MessageType>();
	m_messages.push_back(message);
}

template <typename MessageType>
MessageBus<MessageType>* MessageBus<MessageType>::getBus()
{
	if (m_bus == nullptr)
	{
		std::cout << "bus expired"<< std::endl;
		m_bus.reset(new MessageBus<MessageType>());
	}
	return m_bus.get();
}

template <typename MessageType>
void MessageBus<MessageType>::registerProxy(MessageBusProxy<MessageType>* proxy) {
	auto cursor = m_messages.begin();
	if (m_messages.size() > 0)
		std::advance(cursor, m_messages.size()-1);
	m_proxys.emplace(proxy, cursor);
}

template <typename MessageType>
void MessageBus<MessageType>::unregisterProxy(MessageBusProxy<MessageType>* proxy) {
	auto _search = m_proxys.find(proxy);
	if (_search == m_proxys.end())
		return;
	m_proxys.erase(_search);

	if (m_proxys.size() == 0)
		delete m_bus.release();
}

template <typename MessageType>
MessageType* MessageBus<MessageType>::next(MessageBusProxy<MessageType>* proxy) {
	// TODO : implement next function
	auto& iterator = m_proxys.at(proxy);
	if (iterator == m_messages.end())
		return nullptr;
	return &*(iterator++);
}

template <typename MessageType>
std::unique_ptr<MessageBus<MessageType>> MessageBus<MessageType>::m_bus = nullptr;

template <typename MessageType>
void SendMessage(const MessageType& message) {
	MessageBus<MessageType>::getBus()->push(message);
}

template <typename MessageType, typename ResponseType>
const std::vector<ResponseType>&& RequestMessage(const MessageType& message)
{
	MessageBus<MessageType>::getBus()->request(message);
}

template <typename MessageType, typename ResponseType>
const ResponseType& RequestUnique(const MessageType& message)
{
	auto& response = RequestMessage<MessageType, ResponseType>(message);
	if (response.size() != 1) throw std::runtime_error("More than 1 response");
	return response[0];
}

<|endoftext|>


<commit_before>#ifdef WIN32
/////////////////////////////////////////////////////////////////////////////
// Disable unavoidable warning messages:

//  4103: used #pragma pack to change alignment
//  4114: same type qualifier used more than once
//  4201: nonstandard extension used : nameless struct/union
//  4237: "keyword" reserved for future use
//  4251: class needs to have dll-interface to export class
//  4275: non DLL-interface class used as base for DLL-interface class
//  4290: C++ Exception Specification ignored
//  4503: decorated name length exceeded, name was truncated
//  4786: string too long - truncated to 255 characters

#pragma warning(disable : 4103 4114 4201 4237 4251 4275 4290 4503 4335 4786)

#endif // WIN32

#include <osgProducer/Viewer>

#include <osg/Group>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Texture2D>
#include <osg/PositionAttitudeTransform>
#include <osg/MatrixTransform>
#include <osg/AutoTransform>
#include <osg/CoordinateSystemNode>

#include <osgDB/FileUtils>
#include <osgDB/ReadFile>

#include <osgText/Text>

#include <osgTerrain/DataSet>

#include <osgGA/NodeTrackerManipulator>

class GraphicsContext {
    public:
        GraphicsContext()
        {
            rs = new Producer::RenderSurface;
            rs->setWindowRectangle(0,0,1,1);
            rs->useBorder(false);
            rs->useConfigEventThread(false);
            rs->realize();
        }

        virtual ~GraphicsContext()
        {
        }

    private:
        Producer::ref_ptr<Producer::RenderSurface> rs;
};

osg::Node* createEarth()
{
    osg::ref_ptr<osg::Node> scene;

    {
        std::string filename = osgDB::findDataFile("Images/land_shallow_topo_2048.jpg");

        // make osgTerrain::DataSet quieter..
        osgTerrain::DataSet::setNotifyOffset(1);

        osg::ref_ptr<osgTerrain::DataSet> dataSet = new osgTerrain::DataSet;

        // register the source imagery
        {
            osgTerrain::DataSet::Source* source = new osgTerrain::DataSet::Source(osgTerrain::DataSet::Source::IMAGE, filename);

	    source->setCoordinateSystemPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS);
            source->setCoordinateSystem(osgTerrain::DataSet::coordinateSystemStringToWTK("WGS84"));

 	    source->setGeoTransformPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS_BUT_SCALE_BY_FILE_RESOLUTION);
            source->setGeoTransformFromRange(-180.0, 180.0, -90.0, 90.0);

            dataSet->addSource(source);
        }

        // set up destination database paramters.
        dataSet->setDatabaseType(osgTerrain::DataSet::LOD_DATABASE);
        dataSet->setConvertFromGeographicToGeocentric(true);
        dataSet->setDestinationName("test.osg");

        // load the source data and record sizes.
        dataSet->loadSources();

        GraphicsContext context;
        dataSet->createDestination(30);

        if (dataSet->getDatabaseType()==osgTerrain::DataSet::LOD_DATABASE) dataSet->buildDestination();
        else dataSet->writeDestination();

        scene = dataSet->getDestinationRootNode();
    }

    return scene.release();

}

class ModelPositionCallback : public osg::NodeCallback
{
public:

    ModelPositionCallback():
        _latitude(0.0),
        _longitude(0.0),
        _height(100000.0)
    {
        _rotation.makeRotate(osg::DegreesToRadians(90.0),0.0,0.0,1.0);
    }

    void updateParameters()
    {
        _longitude += ((2.0*osg::PI)/360.0)/20.0;
        _latitude = sin(_longitude);

        // adjust the heading and roll to roughly look ok,
        // but bearing no reality to physics..
        osg::Quat heading;
        heading.makeRotate(osg::DegreesToRadians(90.0)+cos(_longitude),0.0,0.0,1.0);

        osg::Quat roll;
        roll.makeRotate(-_latitude*0.5f,0.0,1.0,0.0);

        _rotation = roll*heading;
    }

    virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
    {
        updateParameters();

        osg::NodePath nodePath = nv->getNodePath();

		osg::AutoTransform * mt = nodePath.empty() ? 0 : dynamic_cast<osg::AutoTransform*>(nodePath.back());
        if (mt)
        {
            osg::CoordinateSystemNode* csn = 0;

            // find coordinate system node from our parental chain
            unsigned int i;
            for(i=0; i<nodePath.size() && csn==0; ++i)
            {
                csn = dynamic_cast<osg::CoordinateSystemNode*>(nodePath[i]);
            }

            if (csn)
            {

                osg::EllipsoidModel* ellipsoid = csn->getEllipsoidModel();
                if (ellipsoid)
                {
                    osg::Matrixd matrix;
                    for(i+=1; i<nodePath.size()-1; ++i)
                    {
                        osg::Transform* transform = nodePath[i]->asTransform();
                        if (transform) transform->computeLocalToWorldMatrix(matrix, nv);
                    }

                    ellipsoid->computeLocalToWorldTransformFromLatLongHeight(_latitude,_longitude,_height,matrix);
                    matrix.preMult(osg::Matrixd::rotate(_rotation));

                   	mt->setPosition(osg::Vec3d(matrix(3,0),matrix(3,1),matrix(3,2)));
					osg::Quat quat;
					quat.set(matrix);
					mt->setRotation(quat);
                }

            }
        }

        traverse(node,nv);
    }

    double                  _latitude;
    double                  _longitude;
    double                  _height;
    osg::Quat               _rotation;
	bool					_useAutoTrans;
};

class FindNamedNodeVisitor : public osg::NodeVisitor
{
public:
    FindNamedNodeVisitor(const std::string& name):
        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
        _name(name) {}

    virtual void apply(osg::Node& node)
    {
        if (node.getName()==_name)
        {
            _foundNodes.push_back(&node);
        }
        traverse(node);
    }

    typedef std::vector< osg::ref_ptr<osg::Node> > NodeList;

    std::string _name;
    NodeList _foundNodes;
};

int main(int argc, char **argv)
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of particle systems.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("--rotate-model angle x y z","Rotate model");
    arguments.getApplicationUsage()->addCommandLineOption("--flight-path","");
    arguments.getApplicationUsage()->addCommandLineOption("--tracker-mode","NODE_CENTER_AND_ROTATION | NODE_CENTER_AND_AZIM | NODE_CENTER");
    arguments.getApplicationUsage()->addCommandLineOption("--rotation-mode","TRACKBALL | ELEVATION_AZIM");

    // construct the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    viewer.getCullSettings().setComputeNearFarMode(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
    viewer.getCullSettings().setNearFarRatio(0.0000000001f);

    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());

    osg::Quat rotation;
    osg::Vec4 vec4;
    while (arguments.read("--rotate-model",vec4[0],vec4[1],vec4[2],vec4[3]))
    {
        osg::Quat local_rotate;
        local_rotate.makeRotate(osg::DegreesToRadians(vec4[0]),vec4[1],vec4[2],vec4[3]);

        rotation = rotation * local_rotate;
    }

    osg::NodeCallback* nc = 0;
    std::string flightpath_filename;
    while (arguments.read("--flight-path",flightpath_filename))
    {
        std::ifstream fin(flightpath_filename.c_str());
        if (fin)
        {
            osg::AnimationPath* path = new osg::AnimationPath;
            path->read(fin);
            nc = new osg::AnimationPathCallback(path);
        }
    }

    osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
    std::string mode;
    while (arguments.read("--tracker-mode",mode))
    {
        if (mode=="NODE_CENTER_AND_ROTATION") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
        else if (mode=="NODE_CENTER_AND_AZIM") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_AZIM;
        else if (mode=="NODE_CENTER") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
        else
        {
            std::cout<<"Unrecognized --tracker-mode option "<<mode<<", valid options are:"<<std::endl;
            std::cout<<"    NODE_CENTER_AND_ROTATION"<<std::endl;
            std::cout<<"    NODE_CENTER_AND_AZIM"<<std::endl;
            std::cout<<"    NODE_CENTER"<<std::endl;
            return 1;
        }
    }

    osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
    while (arguments.read("--rotation-mode",mode))
    {
        if (mode=="TRACKBALL") rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
        else if (mode=="ELEVATION_AZIM") rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
        else
        {
            std::cout<<"Unrecognized --rotation-mode option "<<mode<<", valid options are:"<<std::endl;
            std::cout<<"    TRACKBALL"<<std::endl;
            std::cout<<"    ELEVATION_AZIM"<<std::endl;
            return 1;
        }
    }

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    osg::ref_ptr<osg::MatrixTransform> parent;
    osg::ref_ptr<osg::Node> root;

	osg::Matrix	mat;
	mat.makeScale(osg::Vec3(000000.1, 000000.1, 000000.1));
	parent = new osg::MatrixTransform(mat);

    root = createEarth();

    if (!root) return 0;

	parent->addChild(root.get());

    // add a viewport to the viewer and attach the scene graph.
    viewer.setSceneData(parent.get());

    osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(root.get());

   	if (csn)
   	{
   		osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
       	if (cessna)
       	{
           	double s = 30000.0 / cessna->getBound().radius();

           	osg::MatrixTransform* scaler = new osg::MatrixTransform;
           	scaler->addChild(cessna);
           	scaler->setMatrix(osg::Matrixd::scale(5,5,5));
           	scaler->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL,osg::StateAttribute::ON);

			osg::AutoTransform * mt;

           	mt = new osg::AutoTransform;
			mt->setAutoScaleToScreen(true);
           	mt->addChild(scaler);

			if (!nc)
				nc = new ModelPositionCallback;

           	mt->setUpdateCallback(nc);

           	csn->addChild(mt);

   			osgGA::NodeTrackerManipulator* tm = new osgGA::NodeTrackerManipulator;
    		tm->setTrackerMode(trackerMode);
    		tm->setRotationMode(rotationMode);
			tm->setTrackNode(scaler);

   			unsigned int num = viewer.addCameraManipulator(tm);
    		viewer.selectCameraManipulator(num);
       	}
       	else
       	{
           	std::cout<<"Failed to read cessna.osg"<<std::endl;
       	}
   	}

    // create the windows and run the threads.
    viewer.realize();

    while( !viewer.done() )
    {
        // wait for all cull and draw threads to complete.
        viewer.sync();

        // update the scene by traversing it with the the update visitor which will
        // call all node update callbacks and animations.
        viewer.update();

        // fire off the cull and draw traversals of the scene.
        viewer.frame();

    }

    // wait for all cull and draw threads to complete before exit.
    viewer.sync();

    return 0;
}
<commit_msg>Reverted back to not test version of osgsimulation<commit_after>#ifdef WIN32
/////////////////////////////////////////////////////////////////////////////
// Disable unavoidable warning messages:

//  4103: used #pragma pack to change alignment
//  4114: same type qualifier used more than once
//  4201: nonstandard extension used : nameless struct/union
//  4237: "keyword" reserved for future use
//  4251: class needs to have dll-interface to export class
//  4275: non DLL-interface class used as base for DLL-interface class
//  4290: C++ Exception Specification ignored
//  4503: decorated name length exceeded, name was truncated
//  4786: string too long - truncated to 255 characters

#pragma warning(disable : 4103 4114 4201 4237 4251 4275 4290 4503 4335 4786)

#endif // WIN32

#include <osgProducer/Viewer>

#include <osg/Group>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Texture2D>
#include <osg/PositionAttitudeTransform>
#include <osg/MatrixTransform>
#include <osg/CoordinateSystemNode>

#include <osgDB/FileUtils>
#include <osgDB/ReadFile>

#include <osgText/Text>

#include <osgTerrain/DataSet>

#include <osgGA/NodeTrackerManipulator>

class GraphicsContext {
    public:
        GraphicsContext()
        {
            rs = new Producer::RenderSurface;
            rs->setWindowRectangle(0,0,1,1);
            rs->useBorder(false);
            rs->useConfigEventThread(false);
            rs->realize();
        }

        virtual ~GraphicsContext()
        {
        }

    private:
        Producer::ref_ptr<Producer::RenderSurface> rs;
};

osg::Node* createEarth()
{
    osg::ref_ptr<osg::Node> scene;

    {
        std::string filename = osgDB::findDataFile("Images/land_shallow_topo_2048.jpg");

        // make osgTerrain::DataSet quieter..
        osgTerrain::DataSet::setNotifyOffset(1);

        osg::ref_ptr<osgTerrain::DataSet> dataSet = new osgTerrain::DataSet;

        // register the source imagery
        {
            osgTerrain::DataSet::Source* source = new osgTerrain::DataSet::Source(osgTerrain::DataSet::Source::IMAGE, filename);

	    source->setCoordinateSystemPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS);
            source->setCoordinateSystem(osgTerrain::DataSet::coordinateSystemStringToWTK("WGS84"));

 	    source->setGeoTransformPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS_BUT_SCALE_BY_FILE_RESOLUTION);
            source->setGeoTransformFromRange(-180.0, 180.0, -90.0, 90.0);

            dataSet->addSource(source);
        }

        // set up destination database paramters.
        dataSet->setDatabaseType(osgTerrain::DataSet::LOD_DATABASE);
        dataSet->setConvertFromGeographicToGeocentric(true);
        dataSet->setDestinationName("test.osg");

        // load the source data and record sizes.
        dataSet->loadSources();

        GraphicsContext context;
        dataSet->createDestination(30);

        if (dataSet->getDatabaseType()==osgTerrain::DataSet::LOD_DATABASE) dataSet->buildDestination();
        else dataSet->writeDestination();

        scene = dataSet->getDestinationRootNode();
    }

    return scene.release();

}

class ModelPositionCallback : public osg::NodeCallback
{
public:

    ModelPositionCallback():
        _latitude(0.0),
        _longitude(0.0),
        _height(100000.0)
    {
        _rotation.makeRotate(osg::DegreesToRadians(90.0),0.0,0.0,1.0);
    }

    void updateParameters()
    {
        _longitude += ((2.0*osg::PI)/360.0)/20.0;
    }

    virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
    {
        updateParameters();

        osg::NodePath nodePath = nv->getNodePath();

        osg::MatrixTransform* mt = nodePath.empty() ? 0 : dynamic_cast<osg::MatrixTransform*>(nodePath.back());
        if (mt)
        {
            osg::CoordinateSystemNode* csn = 0;

            // find coordinate system node from our parental chain
            unsigned int i;
            for(i=0; i<nodePath.size() && csn==0; ++i)
            {
                csn = dynamic_cast<osg::CoordinateSystemNode*>(nodePath[i]);
            }

            if (csn)
            {

                osg::EllipsoidModel* ellipsoid = csn->getEllipsoidModel();
                if (ellipsoid)
                {
                    osg::Matrixd matrix;
                    for(i+=1; i<nodePath.size()-1; ++i)
                    {
                        osg::Transform* transform = nodePath[i]->asTransform();
                        if (transform) transform->computeLocalToWorldMatrix(matrix, nv);
                    }

                    //osg::Matrixd matrix;
                    ellipsoid->computeLocalToWorldTransformFromLatLongHeight(_latitude,_longitude,_height,matrix);
                    matrix.preMult(osg::Matrixd::rotate(_rotation));

                    mt->setMatrix(matrix);
                }

            }
        }

        traverse(node,nv);
    }

    double                  _latitude;
    double                  _longitude;
    double                  _height;
    osg::Quat               _rotation;
};

class FindNamedNodeVisitor : public osg::NodeVisitor
{
public:
    FindNamedNodeVisitor(const std::string& name):
        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
        _name(name) {}

    virtual void apply(osg::Node& node)
    {
        if (node.getName()==_name)
        {
            _foundNodes.push_back(&node);
        }
        traverse(node);
    }

    typedef std::vector< osg::ref_ptr<osg::Node> > NodeList;

    std::string _name;
    NodeList _foundNodes;
};

int main(int argc, char **argv)
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of particle systems.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");

    // construct the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    viewer.getCullSettings().setComputeNearFarMode(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
    viewer.getCullSettings().setNearFarRatio(0.00001f);

    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());

    osg::Quat rotation;
    osg::Vec4 vec4;
    while (arguments.read("--rotate-model",vec4[0],vec4[1],vec4[2],vec4[3]))
    {
        osg::Quat local_rotate;
        local_rotate.makeRotate(osg::DegreesToRadians(vec4[0]),vec4[1],vec4[2],vec4[3]);

        rotation = rotation * local_rotate;
    }

    osg::NodeCallback* nc = 0;
    std::string flightpath_filename;
    while (arguments.read("--flight-path",flightpath_filename))
    {
        std::ifstream fin(flightpath_filename.c_str());
        if (fin)
        {
            osg::AnimationPath* path = new osg::AnimationPath;
            path->read(fin);
            nc = new osg::AnimationPathCallback(path);
        }
    }

    osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
    std::string mode;
    while (arguments.read("--tracker-mode",mode))
    {
        if (mode=="NODE_CENTER_AND_ROTATION") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
        else if (mode=="NODE_CENTER_AND_AZIM") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_AZIM;
        else if (mode=="NODE_CENTER") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
        else
        {
            std::cout<<"Unrecognized --tracker-mode option "<<mode<<", valid options are:"<<std::endl;
            std::cout<<"    NODE_CENTER_AND_ROTATION"<<std::endl;
            std::cout<<"    NODE_CENTER_AND_AZIM"<<std::endl;
            std::cout<<"    NODE_CENTER"<<std::endl;
            return 1;
        }
    }

    osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
    while (arguments.read("--rotation-mode",mode))
    {
        if (mode=="TRACKBALL") rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
        else if (mode=="ELEVATION_AZIM") rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
        else
        {
            std::cout<<"Unrecognized --rotation-mode option "<<mode<<", valid options are:"<<std::endl;
            std::cout<<"    TRACKBALL"<<std::endl;
            std::cout<<"    ELEVATION_AZIM"<<std::endl;
            return 1;
        }
    }

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    osg::ref_ptr<osg::Node> root = createEarth();

    if (!root) return 0;

    // add a viewport to the viewer and attach the scene graph.
    viewer.setSceneData(root.get());

    osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(root.get());
    if (csn)
    {
        osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
        if (cessna)
        {
            double s = 30000.0 / cessna->getBound().radius();

            osg::MatrixTransform* scaler = new osg::MatrixTransform;
            scaler->addChild(cessna);
            scaler->setMatrix(osg::Matrixd::scale(s,s,s)*osg::Matrixd::rotate(rotation));
            scaler->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL,osg::StateAttribute::ON);

            osg::MatrixTransform* mt = new osg::MatrixTransform;
            mt->addChild(scaler);

            if (!nc) nc = new ModelPositionCallback;

            mt->setUpdateCallback(nc);

            csn->addChild(mt);

            osgGA::NodeTrackerManipulator* tm = new osgGA::NodeTrackerManipulator;
            tm->setTrackerMode(trackerMode);
            tm->setRotationMode(rotationMode);
            tm->setTrackNode(scaler);

            unsigned int num = viewer.addCameraManipulator(tm);
            viewer.selectCameraManipulator(num);
        }
        else
        {
             std::cout<<"Failed to read cessna.osg"<<std::endl;
        }
    }

    // create the windows and run the threads.
    viewer.realize();

    while( !viewer.done() )
    {
        // wait for all cull and draw threads to complete.
        viewer.sync();

        // update the scene by traversing it with the the update visitor which will
        // call all node update callbacks and animations.
        viewer.update();

        // fire off the cull and draw traversals of the scene.
        viewer.frame();

    }

    // wait for all cull and draw threads to complete before exit.
    viewer.sync();

    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: eventsconfiguration.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:03:07 $
 *
 *  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_XML_EVENTSCONFIGURATION_HXX_
#include <xml/eventsconfiguration.hxx>
#endif

#ifndef __FRAMEWORK_CLASSES_EVENTSDOCUMENTHANDLER_HXX_
#include <xml/eventsdocumenthandler.hxx>
#endif

#ifndef __FRAMEWORK_XML_SAXNAMESPACEFILTER_HXX_
#include <xml/saxnamespacefilter.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_
#include <com/sun/star/xml/sax/XParser.hpp>
#endif

#ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_
#include <com/sun/star/io/XActiveDataSource.hpp>
#endif

#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _UNOTOOLS_PROCESSFACTORY_HXX
#include <comphelper/processfactory.hxx>
#endif

#ifndef _UTL_STREAM_WRAPPER_HXX_
#include <unotools/streamwrap.hxx>
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::io;

namespace framework
{

static Reference< XParser > GetSaxParser(
    // #110897#
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory
    )
{
    //Reference< XMultiServiceFactory > xServiceManager = ::comphelper::getProcessServiceFactory();
    //return Reference< XParser >( xServiceManager->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.xml.sax.Parser" )), UNO_QUERY);
    return Reference< XParser >( xServiceFactory->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.xml.sax.Parser" )), UNO_QUERY);
}

static Reference< XDocumentHandler > GetSaxWriter(
    // #110897#
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory
    )
{
    //Reference< XMultiServiceFactory > xServiceManager = ::comphelper::getProcessServiceFactory();
    //return Reference< XDocumentHandler >( xServiceManager->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.xml.sax.Writer" )), UNO_QUERY) ;
    return Reference< XDocumentHandler >( xServiceFactory->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.xml.sax.Writer" )), UNO_QUERY) ;
}

// #110897#
sal_Bool EventsConfiguration::LoadEventsConfig(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
    SvStream& rInStream, EventsConfig& aItems )
{
    Reference< XParser > xParser( GetSaxParser( xServiceFactory ) );
    Reference< XInputStream > xInputStream(
                                (::cppu::OWeakObject *)new utl::OInputStreamWrapper( rInStream ),
                                UNO_QUERY );

    // connect stream to input stream to the parser
    InputSource aInputSource;

    aInputSource.aInputStream = xInputStream;

    // create namespace filter and set events document handler inside to support xml namespaces
    Reference< XDocumentHandler > xDocHandler( new OReadEventsDocumentHandler( aItems ));
    Reference< XDocumentHandler > xFilter( new SaxNamespaceFilter( xDocHandler ));

    // connect parser and filter
    xParser->setDocumentHandler( xFilter );

    try
    {
        xParser->parseStream( aInputSource );
        return sal_True;
    }
    catch ( RuntimeException& )
    {
        return sal_False;
    }
    catch( SAXException& )
    {
        return sal_False;
    }
    catch( ::com::sun::star::io::IOException& )
    {
        return sal_False;
    }

    return sal_False;
}

// #110897#
sal_Bool EventsConfiguration::StoreEventsConfig(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
    SvStream& rOutStream, const EventsConfig& aItems )
{
    Reference< XDocumentHandler > xWriter( GetSaxWriter( xServiceFactory ) );

    Reference< XOutputStream > xOutputStream(
                                (::cppu::OWeakObject *)new utl::OOutputStreamWrapper( rOutStream ),
                                UNO_QUERY );

    Reference< ::com::sun::star::io::XActiveDataSource> xDataSource( xWriter , UNO_QUERY );
    xDataSource->setOutputStream( xOutputStream );

    try
    {
        OWriteEventsDocumentHandler aWriteEventsDocumentHandler( aItems, xWriter );
        aWriteEventsDocumentHandler.WriteEventsDocument();
        return sal_True;
    }
    catch ( RuntimeException& )
    {
        return sal_False;
    }
    catch ( SAXException& )
    {
        return sal_False;
    }
    catch ( ::com::sun::star::io::IOException& )
    {
        return sal_False;
    }

    return sal_False;
}

}
<commit_msg>INTEGRATION: CWS warnings01 (1.4.32); FILE MERGED 2005/11/16 15:20:50 pl 1.4.32.1: #i55991# removed warnings<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: eventsconfiguration.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 11:45:14 $
 *
 *  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_XML_EVENTSCONFIGURATION_HXX_
#include <xml/eventsconfiguration.hxx>
#endif

#ifndef __FRAMEWORK_CLASSES_EVENTSDOCUMENTHANDLER_HXX_
#include <xml/eventsdocumenthandler.hxx>
#endif

#ifndef __FRAMEWORK_XML_SAXNAMESPACEFILTER_HXX_
#include <xml/saxnamespacefilter.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_
#include <com/sun/star/xml/sax/XParser.hpp>
#endif

#ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_
#include <com/sun/star/io/XActiveDataSource.hpp>
#endif

#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _UNOTOOLS_PROCESSFACTORY_HXX
#include <comphelper/processfactory.hxx>
#endif

#ifndef _UTL_STREAM_WRAPPER_HXX_
#include <unotools/streamwrap.hxx>
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::io;

namespace framework
{

static Reference< XParser > GetSaxParser(
    // #110897#
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory
    )
{
    //Reference< XMultiServiceFactory > xServiceManager = ::comphelper::getProcessServiceFactory();
    //return Reference< XParser >( xServiceManager->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.xml.sax.Parser" )), UNO_QUERY);
    return Reference< XParser >( xServiceFactory->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.xml.sax.Parser" )), UNO_QUERY);
}

static Reference< XDocumentHandler > GetSaxWriter(
    // #110897#
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory
    )
{
    //Reference< XMultiServiceFactory > xServiceManager = ::comphelper::getProcessServiceFactory();
    //return Reference< XDocumentHandler >( xServiceManager->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.xml.sax.Writer" )), UNO_QUERY) ;
    return Reference< XDocumentHandler >( xServiceFactory->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.xml.sax.Writer" )), UNO_QUERY) ;
}

// #110897#
sal_Bool EventsConfiguration::LoadEventsConfig(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
    SvStream& rInStream, EventsConfig& aItems )
{
    Reference< XParser > xParser( GetSaxParser( xServiceFactory ) );
    Reference< XInputStream > xInputStream(
                                (::cppu::OWeakObject *)new utl::OInputStreamWrapper( rInStream ),
                                UNO_QUERY );

    // connect stream to input stream to the parser
    InputSource aInputSource;

    aInputSource.aInputStream = xInputStream;

    // create namespace filter and set events document handler inside to support xml namespaces
    Reference< XDocumentHandler > xDocHandler( new OReadEventsDocumentHandler( aItems ));
    Reference< XDocumentHandler > xFilter( new SaxNamespaceFilter( xDocHandler ));

    // connect parser and filter
    xParser->setDocumentHandler( xFilter );

    try
    {
        xParser->parseStream( aInputSource );
        return sal_True;
    }
    catch ( RuntimeException& )
    {
        return sal_False;
    }
    catch( SAXException& )
    {
        return sal_False;
    }
    catch( ::com::sun::star::io::IOException& )
    {
        return sal_False;
    }
}

// #110897#
sal_Bool EventsConfiguration::StoreEventsConfig(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
    SvStream& rOutStream, const EventsConfig& aItems )
{
    Reference< XDocumentHandler > xWriter( GetSaxWriter( xServiceFactory ) );

    Reference< XOutputStream > xOutputStream(
                                (::cppu::OWeakObject *)new utl::OOutputStreamWrapper( rOutStream ),
                                UNO_QUERY );

    Reference< ::com::sun::star::io::XActiveDataSource> xDataSource( xWriter , UNO_QUERY );
    xDataSource->setOutputStream( xOutputStream );

    try
    {
        OWriteEventsDocumentHandler aWriteEventsDocumentHandler( aItems, xWriter );
        aWriteEventsDocumentHandler.WriteEventsDocument();
        return sal_True;
    }
    catch ( RuntimeException& )
    {
        return sal_False;
    }
    catch ( SAXException& )
    {
        return sal_False;
    }
    catch ( ::com::sun::star::io::IOException& )
    {
        return sal_False;
    }
}

}
<|endoftext|>


<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

#include "AccumulateReporter.h"

registerMooseObject("MooseApp", AccumulateReporter);

InputParameters
AccumulateReporter::validParams()
{
  InputParameters params = GeneralReporter::validParams();
  params.addClassDescription("Reporter the accumulates the value of a inputted reporter value over "
                             "time into a vector reporter value of the same type.");
  params.addRequiredParam<std::vector<ReporterName>>("reporters", "The reporters to accumulate.");

  params.set<ExecFlagEnum>("execute_on") = {EXEC_INITIAL, EXEC_TIMESTEP_END};
  params.suppressParameter<ExecFlagEnum>("execute_on");
  return params;
}

AccumulateReporter::AccumulateReporter(const InputParameters & parameters)
  : GeneralReporter(parameters)
{
}

void
AccumulateReporter::initialSetup()
{
  const ReporterData & rdata = _fe_problem.getReporterData();
  for (const auto & rname : getParam<std::vector<ReporterName>>("reporters"))
  {
    if (!rdata.hasReporterValue(rname))
      paramError("reporters", "Reporter ", rname, " does not exist.");

    if (!declareAccumulateHelper<int>(rname) && !declareAccumulateHelper<Real>(rname) &&
        !declareAccumulateHelper<dof_id_type>(rname) &&
        !declareAccumulateHelper<std::string>(rname) &&
        !declareAccumulateHelper<std::vector<int>>(rname) &&
        !declareAccumulateHelper<std::vector<Real>>(rname) &&
        !declareAccumulateHelper<std::vector<std::string>>(rname) &&
        !declareAccumulateHelper<std::vector<dof_id_type>>(rname))
      paramError("reporters",
                 "Reporter value ",
                 rname,
                 " is of unsupported type ",
                 rdata.getReporterContextBase(rname).type(),
                 ".");
  }
}

void
AccumulateReporter::execute()
{
  unsigned int ind = static_cast<unsigned int>(_t_step);
  for (auto & val : _accumulated_values)
    val->accumulate(ind);
}
<commit_msg>Fixup description of accumulate reporter, refs #16248<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

#include "AccumulateReporter.h"

registerMooseObject("MooseApp", AccumulateReporter);

InputParameters
AccumulateReporter::validParams()
{
  InputParameters params = GeneralReporter::validParams();
  params.addClassDescription("Reporter which accumulates the value of a inputted reporter value "
                             "over time into a vector reporter value of the same type.");
  params.addRequiredParam<std::vector<ReporterName>>("reporters", "The reporters to accumulate.");

  params.set<ExecFlagEnum>("execute_on") = {EXEC_INITIAL, EXEC_TIMESTEP_END};
  params.suppressParameter<ExecFlagEnum>("execute_on");
  return params;
}

AccumulateReporter::AccumulateReporter(const InputParameters & parameters)
  : GeneralReporter(parameters)
{
}

void
AccumulateReporter::initialSetup()
{
  const ReporterData & rdata = _fe_problem.getReporterData();
  for (const auto & rname : getParam<std::vector<ReporterName>>("reporters"))
  {
    if (!rdata.hasReporterValue(rname))
      paramError("reporters", "Reporter ", rname, " does not exist.");

    if (!declareAccumulateHelper<int>(rname) && !declareAccumulateHelper<Real>(rname) &&
        !declareAccumulateHelper<dof_id_type>(rname) &&
        !declareAccumulateHelper<std::string>(rname) &&
        !declareAccumulateHelper<std::vector<int>>(rname) &&
        !declareAccumulateHelper<std::vector<Real>>(rname) &&
        !declareAccumulateHelper<std::vector<std::string>>(rname) &&
        !declareAccumulateHelper<std::vector<dof_id_type>>(rname))
      paramError("reporters",
                 "Reporter value ",
                 rname,
                 " is of unsupported type ",
                 rdata.getReporterContextBase(rname).type(),
                 ".");
  }
}

void
AccumulateReporter::execute()
{
  unsigned int ind = static_cast<unsigned int>(_t_step);
  for (auto & val : _accumulated_values)
    val->accumulate(ind);
}
<|endoftext|>


<commit_before>/*
   Copyright (c) 2010, The Mineserver Project
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
 * Neither the name of the The Mineserver Project nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdlib.h>
#ifdef WIN32
  #include <conio.h>
  #include <winsock2.h>
  #include <process.h>
#else
  #include <sys/socket.h>
  #include <netinet/in.h>
  #include <arpa/inet.h>
  #include <string.h>
  #include <netdb.h>
  #include <unistd.h>
#endif
#include <sys/types.h>
#include <fcntl.h>
#include <cassert>
#include <deque>
#include <map>
#include <iostream>
#include <fstream>
#include <event.h>
#include <ctime>
#include <vector>
#include <zlib.h>
#include <signal.h>

#include "constants.h"
#include "mineserver.h"
#include "logger.h"
#include "sockets.h"
#include "tools.h"
#include "map.h"
#include "user.h"
#include "chat.h"
#include "mapgen.h"
#include "config.h"
#include "nbt.h"
#include "packets.h"
#include "physics.h"
#include "plugin.h"

#ifdef WIN32
static bool quit = false;
#endif

int setnonblock(int fd)
{
  #ifdef WIN32
  u_long iMode = 1;
  ioctlsocket(fd, FIONBIO, &iMode);
  #else
  int flags;

  flags  = fcntl(fd, F_GETFL);
  flags |= O_NONBLOCK;
  fcntl(fd, F_SETFL, flags);
  #endif

  return 1;
}

//Handle signals
void sighandler(int sig_num)
{
  Mineserver::Get().Stop();
}

int main(int argc, char *argv[])
{
  signal(SIGTERM, sighandler);
  signal(SIGINT, sighandler);

  srand(time(NULL));

  return Mineserver::Get().Run(argc, argv);
}

Mineserver::Mineserver()
{
}

event_base *Mineserver::GetEventBase()
{
  return m_eventBase;
}

int Mineserver::Run(int argc, char *argv[])
{
  uint32 starttime = (uint32)time(0);
  uint32 tick      = (uint32)time(0);

  initConstants();

  std::string file_config;
  file_config.assign(CONFIG_FILE);

  if (argc > 1)
    file_config.assign(argv[1]);

  // Initialize conf
  Conf::get().load(file_config);

  // Write PID to file
  std::ofstream pid_out((Conf::get().sValue("pid_file")).c_str());
  if (!pid_out.fail())
     #ifdef WIN32
     pid_out << _getpid();
     #else
     pid_out << getpid();
     #endif
  pid_out.close();

  // Load admin, banned and whitelisted users
  Chat::get().loadAdmins(Conf::get().sValue("admin_file"));
  Chat::get().loadBanned(Conf::get().sValue("banned_file"));
  Chat::get().loadWhitelist(Conf::get().sValue("whitelist_file"));
  // Load MOTD
  Chat::get().checkMotd(Conf::get().sValue("motd_file"));

  // Set physics enable state according to config
  Physics::get().enabled = (Conf::get().bValue("liquid_physics"));

  // Initialize map
  Map::get().initMap();

  // Initialize packethandler
  PacketHandler::get().initPackets();

  // Load ip from config
  std::string ip = Conf::get().sValue("ip");

  // Load port from config
  int port = Conf::get().iValue("port");

  // Initialize plugins
  Plugin::get().init();

#ifdef WIN32
  WSADATA wsaData;
  int iResult;
  // Initialize Winsock
  iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
  if(iResult != 0)
  {
    printf("WSAStartup failed with error: %d\n", iResult);
    return EXIT_FAILURE;
  }
#endif

  struct sockaddr_in addresslisten;
  int reuse             = 1;

  m_eventBase = (event_base *)event_init();
#ifdef WIN32
  m_socketlisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
#else
  m_socketlisten = socket(AF_INET, SOCK_STREAM, 0);
#endif

  if(m_socketlisten < 0)
  {
    std::cerr << "Failed to create listen socket" << std::endl;
    return 1;
  }

  memset(&addresslisten, 0, sizeof(addresslisten));

  addresslisten.sin_family      = AF_INET;
  addresslisten.sin_addr.s_addr = inet_addr(ip.c_str());
  addresslisten.sin_port        = htons(port);

  setsockopt(m_socketlisten, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse));

  //Bind to port
  if(bind(m_socketlisten, (struct sockaddr *)&addresslisten, sizeof(addresslisten)) < 0)
  {
    std::cerr << "Failed to bind" << std::endl;
    return 1;
  }

  if(listen(m_socketlisten, 5) < 0)
  {
    std::cerr << "Failed to listen to socket" << std::endl;
    return 1;
  }

  setnonblock(m_socketlisten);
  event_set(&m_listenEvent, m_socketlisten, EV_WRITE|EV_READ|EV_PERSIST, accept_callback, NULL);
  event_add(&m_listenEvent, NULL);

  std::cout << std::endl<<
  "   _____  .__  "<<
  std::endl<<
  "  /     \\ |__| ____   ____   ______ ______________  __ ___________ "<<
  std::endl<<
  " /  \\ /  \\|  |/    \\_/ __ \\ /  ___// __ \\_  __ \\  \\/ // __ \\_  __ \\"<<
  std::endl<<
  "/    Y    \\  |   |  \\  ___/ \\___ \\\\  ___/|  | \\/\\   /\\  ___/|  | \\/"<<
  std::endl<<
  "\\____|__  /__|___|  /\\___  >____  >\\___  >__|    \\_/  \\___  >__|   "<<
  std::endl<<
  "        \\/        \\/     \\/     \\/     \\/                 \\/       "<<
  std::endl<<
  "Version " << VERSION <<" by Fador & Nredor"<<
  std::endl << std::endl;

  if(ip == "0.0.0.0")
  {
    std::cout << "Listening on port " << port << std::endl;
    // Print all local IPs
    char name[255];
    gethostname ( name, sizeof(name));
    struct hostent *hostinfo = gethostbyname(name);
    std::cout << "Server IP(s): ";
    int ipIndex = 0;
    while(hostinfo->h_addr_list[ipIndex]) {
        if(ipIndex > 0) { std::cout << ", "; }
        char *ip = inet_ntoa(*(struct in_addr *)hostinfo->h_addr_list[ipIndex++]);
        std::cout << ip;
    }
    std::cout << std::endl;
  }
  else
  {
    std::cout << "Listening on " << ip << ":" << port << std::endl;
  }

  timeval loopTime;
  loopTime.tv_sec  = 0;
  loopTime.tv_usec = 200000; //200ms

  m_running=true;
  event_base_loopexit(m_eventBase, &loopTime);
  while(m_running && event_base_loop(m_eventBase, 0) == 0)
  {
    if(time(0)-starttime > 10)
    {
      starttime = (uint32)time(0);
      std::cout << "Currently " << Users.size() << " users in!" << std::endl;

      //If users, ping them
      if(Users.size() > 0)
      {
        //0x00 package
        uint8 data = 0;
        Users[0]->sendAll(&data, 1);

        //Send server time
        Packet pkt;
        pkt << (sint8)PACKET_TIME_UPDATE << (sint64)Map::get().mapTime;
        Users[0]->sendAll((uint8*)pkt.getWrite(), pkt.getWriteLen());
      }

      //Try to load release time from config
      int map_release_time = Conf::get().iValue("map_release_time");

      //Release chunks not used in <map_release_time> seconds
      std::vector<uint32> toRelease;
      for(std::map<uint32, int>::const_iterator it = Map::get().mapLastused.begin();
          it != Map::get().mapLastused.end();
          ++it)
      {
        if(Map::get().mapLastused[it->first] <= time(0)-map_release_time)
          toRelease.push_back(it->first);
      }

      int x_temp, z_temp;
      for(unsigned i = 0; i < toRelease.size(); i++)
      {
        Map::get().idToPos(toRelease[i], &x_temp, &z_temp);
        Map::get().releaseMap(x_temp, z_temp);
      }
    }

    //Every second
    if(time(0)-tick > 0)
    {
      tick = (uint32)time(0);
      //Loop users
      for(unsigned int i = 0; i < Users.size(); i++)
      {
        Users[i]->pushMap();
        Users[i]->popMap();
      }
      Map::get().mapTime+=20;
      if(Map::get().mapTime>=24000) Map::get().mapTime=0;
    }

    //Physics simulation every 200ms
    Physics::get().update();

    event_base_loopexit(m_eventBase, &loopTime);
  }

  Map::get().freeMap();

  #ifdef WIN32
  closesocket(m_socketlisten);
  #else
    close(m_socketlisten);
  #endif

  return EXIT_SUCCESS;
}

bool Mineserver::Stop()
{
  m_running=false;

  return true;
}
<commit_msg>Removing the PID file when the software close.<commit_after>/*
   Copyright (c) 2010, The Mineserver Project
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
 * Neither the name of the The Mineserver Project nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdlib.h>
#ifdef WIN32
  #include <conio.h>
  #include <winsock2.h>
  #include <process.h>
#else
  #include <sys/socket.h>
  #include <netinet/in.h>
  #include <arpa/inet.h>
  #include <string.h>
  #include <netdb.h>
  #include <unistd.h>
#endif
#include <sys/types.h>
#include <fcntl.h>
#include <cassert>
#include <deque>
#include <map>
#include <iostream>
#include <fstream>
#include <event.h>
#include <ctime>
#include <vector>
#include <zlib.h>
#include <signal.h>

#include "constants.h"
#include "mineserver.h"
#include "logger.h"
#include "sockets.h"
#include "tools.h"
#include "map.h"
#include "user.h"
#include "chat.h"
#include "mapgen.h"
#include "config.h"
#include "nbt.h"
#include "packets.h"
#include "physics.h"
#include "plugin.h"

#ifdef WIN32
static bool quit = false;
#endif

int setnonblock(int fd)
{
  #ifdef WIN32
  u_long iMode = 1;
  ioctlsocket(fd, FIONBIO, &iMode);
  #else
  int flags;

  flags  = fcntl(fd, F_GETFL);
  flags |= O_NONBLOCK;
  fcntl(fd, F_SETFL, flags);
  #endif

  return 1;
}

//Handle signals
void sighandler(int sig_num)
{
  Mineserver::Get().Stop();
}

int main(int argc, char *argv[])
{
  signal(SIGTERM, sighandler);
  signal(SIGINT, sighandler);

  srand(time(NULL));

  return Mineserver::Get().Run(argc, argv);
}

Mineserver::Mineserver()
{
}

event_base *Mineserver::GetEventBase()
{
  return m_eventBase;
}

int Mineserver::Run(int argc, char *argv[])
{
  uint32 starttime = (uint32)time(0);
  uint32 tick      = (uint32)time(0);

  initConstants();

  std::string file_config;
  file_config.assign(CONFIG_FILE);

  if (argc > 1)
    file_config.assign(argv[1]);

  // Initialize conf
  Conf::get().load(file_config);

  // Write PID to file
  std::ofstream pid_out((Conf::get().sValue("pid_file")).c_str());
  if (!pid_out.fail())
     #ifdef WIN32
     pid_out << _getpid();
     #else
     pid_out << getpid();
     #endif
  pid_out.close();

  // Load admin, banned and whitelisted users
  Chat::get().loadAdmins(Conf::get().sValue("admin_file"));
  Chat::get().loadBanned(Conf::get().sValue("banned_file"));
  Chat::get().loadWhitelist(Conf::get().sValue("whitelist_file"));
  // Load MOTD
  Chat::get().checkMotd(Conf::get().sValue("motd_file"));

  // Set physics enable state according to config
  Physics::get().enabled = (Conf::get().bValue("liquid_physics"));

  // Initialize map
  Map::get().initMap();

  // Initialize packethandler
  PacketHandler::get().initPackets();

  // Load ip from config
  std::string ip = Conf::get().sValue("ip");

  // Load port from config
  int port = Conf::get().iValue("port");

  // Initialize plugins
  Plugin::get().init();

#ifdef WIN32
  WSADATA wsaData;
  int iResult;
  // Initialize Winsock
  iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
  if(iResult != 0)
  {
    printf("WSAStartup failed with error: %d\n", iResult);
    return EXIT_FAILURE;
  }
#endif

  struct sockaddr_in addresslisten;
  int reuse             = 1;

  m_eventBase = (event_base *)event_init();
#ifdef WIN32
  m_socketlisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
#else
  m_socketlisten = socket(AF_INET, SOCK_STREAM, 0);
#endif

  if(m_socketlisten < 0)
  {
    std::cerr << "Failed to create listen socket" << std::endl;
    return 1;
  }

  memset(&addresslisten, 0, sizeof(addresslisten));

  addresslisten.sin_family      = AF_INET;
  addresslisten.sin_addr.s_addr = inet_addr(ip.c_str());
  addresslisten.sin_port        = htons(port);

  setsockopt(m_socketlisten, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse));

  //Bind to port
  if(bind(m_socketlisten, (struct sockaddr *)&addresslisten, sizeof(addresslisten)) < 0)
  {
    std::cerr << "Failed to bind" << std::endl;
    return 1;
  }

  if(listen(m_socketlisten, 5) < 0)
  {
    std::cerr << "Failed to listen to socket" << std::endl;
    return 1;
  }

  setnonblock(m_socketlisten);
  event_set(&m_listenEvent, m_socketlisten, EV_WRITE|EV_READ|EV_PERSIST, accept_callback, NULL);
  event_add(&m_listenEvent, NULL);

  std::cout << std::endl<<
  "   _____  .__  "<<
  std::endl<<
  "  /     \\ |__| ____   ____   ______ ______________  __ ___________ "<<
  std::endl<<
  " /  \\ /  \\|  |/    \\_/ __ \\ /  ___// __ \\_  __ \\  \\/ // __ \\_  __ \\"<<
  std::endl<<
  "/    Y    \\  |   |  \\  ___/ \\___ \\\\  ___/|  | \\/\\   /\\  ___/|  | \\/"<<
  std::endl<<
  "\\____|__  /__|___|  /\\___  >____  >\\___  >__|    \\_/  \\___  >__|   "<<
  std::endl<<
  "        \\/        \\/     \\/     \\/     \\/                 \\/       "<<
  std::endl<<
  "Version " << VERSION <<" by Fador & Nredor"<<
  std::endl << std::endl;

  if(ip == "0.0.0.0")
  {
    std::cout << "Listening on port " << port << std::endl;
    // Print all local IPs
    char name[255];
    gethostname ( name, sizeof(name));
    struct hostent *hostinfo = gethostbyname(name);
    std::cout << "Server IP(s): ";
    int ipIndex = 0;
    while(hostinfo->h_addr_list[ipIndex]) {
        if(ipIndex > 0) { std::cout << ", "; }
        char *ip = inet_ntoa(*(struct in_addr *)hostinfo->h_addr_list[ipIndex++]);
        std::cout << ip;
    }
    std::cout << std::endl;
  }
  else
  {
    std::cout << "Listening on " << ip << ":" << port << std::endl;
  }

  timeval loopTime;
  loopTime.tv_sec  = 0;
  loopTime.tv_usec = 200000; //200ms

  m_running=true;
  event_base_loopexit(m_eventBase, &loopTime);
  while(m_running && event_base_loop(m_eventBase, 0) == 0)
  {
    if(time(0)-starttime > 10)
    {
      starttime = (uint32)time(0);
      std::cout << "Currently " << Users.size() << " users in!" << std::endl;

      //If users, ping them
      if(Users.size() > 0)
      {
        //0x00 package
        uint8 data = 0;
        Users[0]->sendAll(&data, 1);

        //Send server time
        Packet pkt;
        pkt << (sint8)PACKET_TIME_UPDATE << (sint64)Map::get().mapTime;
        Users[0]->sendAll((uint8*)pkt.getWrite(), pkt.getWriteLen());
      }

      //Try to load release time from config
      int map_release_time = Conf::get().iValue("map_release_time");

      //Release chunks not used in <map_release_time> seconds
      std::vector<uint32> toRelease;
      for(std::map<uint32, int>::const_iterator it = Map::get().mapLastused.begin();
          it != Map::get().mapLastused.end();
          ++it)
      {
        if(Map::get().mapLastused[it->first] <= time(0)-map_release_time)
          toRelease.push_back(it->first);
      }

      int x_temp, z_temp;
      for(unsigned i = 0; i < toRelease.size(); i++)
      {
        Map::get().idToPos(toRelease[i], &x_temp, &z_temp);
        Map::get().releaseMap(x_temp, z_temp);
      }
    }

    //Every second
    if(time(0)-tick > 0)
    {
      tick = (uint32)time(0);
      //Loop users
      for(unsigned int i = 0; i < Users.size(); i++)
      {
        Users[i]->pushMap();
        Users[i]->popMap();
      }
      Map::get().mapTime+=20;
      if(Map::get().mapTime>=24000) Map::get().mapTime=0;
    }

    //Physics simulation every 200ms
    Physics::get().update();

    event_base_loopexit(m_eventBase, &loopTime);
  }

  Map::get().freeMap();

  #ifdef WIN32
  closesocket(m_socketlisten);
  #else
    close(m_socketlisten);
  #endif

  unlink((Conf::get().sValue("pid_file")).c_str());

  return EXIT_SUCCESS;
}

bool Mineserver::Stop()
{
  m_running=false;

  return true;
}
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/
#ifndef itkSpecialCoordinatesImageToVTKStructuredGridFilter_hxx
#define itkSpecialCoordinatesImageToVTKStructuredGridFilter_hxx

#include "itkSpecialCoordinatesImageToVTKStructuredGridFilter.h"

#include "itkImageRegionConstIteratorWithIndex.h"
#include "itkPixelTraits.h"

#include "vtkPointData.h"
#include "vtkNew.h"
#include "vtkPoints.h"
#include "vtkDataArray.h"
#include "vtkDoubleArray.h"
#include "vtkFloatArray.h"
#include "vtkLongArray.h"
#include "vtkUnsignedLongArray.h"
#include "vtkIntArray.h"
#include "vtkUnsignedIntArray.h"
#include "vtkShortArray.h"
#include "vtkUnsignedShortArray.h"
#include "vtkUnsignedCharArray.h"
#include "vtkSignedCharArray.h"

#include <cstring>

namespace itk
{

template< typename TInputImage >
SpecialCoordinatesImageToVTKStructuredGridFilter< TInputImage >
::SpecialCoordinatesImageToVTKStructuredGridFilter()
{
  this->SetNumberOfRequiredInputs( 1 );

  this->SetPrimaryOutputName( "StructuredGrid" );
  this->SetNumberOfRequiredOutputs( 1 );
  this->ReleaseDataBeforeUpdateFlagOff();

  typename DecoratedStructuredGridPointerType::Pointer decoratedStructuredGrid =
        itkDynamicCastInDebugMode< DecoratedStructuredGridPointerType * >( this->MakeOutput(0).GetPointer() );
  decoratedStructuredGrid->Set( m_StructuredGrid );
  this->ProcessObject::SetNthOutput( 0, decoratedStructuredGrid );
}

template< typename TInputImage >
SpecialCoordinatesImageToVTKStructuredGridFilter< TInputImage >
::~SpecialCoordinatesImageToVTKStructuredGridFilter()
{
}

template< typename TInputImage >
DataObject::Pointer
SpecialCoordinatesImageToVTKStructuredGridFilter< TInputImage >
::MakeOutput( DataObjectPointerArraySizeType output )
{
  switch ( output )
    {
    case 0:
      {
      m_StructuredGrid = vtkSmartPointer< vtkStructuredGrid >::New();
      DecoratedStructuredGridPointerType::Pointer decoratedStructuredGrid = DecoratedStructuredGridPointerType::New();
      decoratedStructuredGrid->Set( m_StructuredGrid );
      return decoratedStructuredGrid.GetPointer();
      }
    default:
      itkExceptionMacro( "MakeOutput request for an output number larger than the expected number of outputs." );
      return ITK_NULLPTR;
    }
}

template< typename TInputImage >
void
SpecialCoordinatesImageToVTKStructuredGridFilter< TInputImage >
::SetInput(const InputImageType *input)
{
  // Process object is not const-correct so the const_cast is required here
  this->ProcessObject::SetNthInput( 0, const_cast< InputImageType * >( input ) );
}

template< typename TInputImage >
const typename SpecialCoordinatesImageToVTKStructuredGridFilter< TInputImage >::InputImageType *
SpecialCoordinatesImageToVTKStructuredGridFilter< TInputImage >
::GetInput() const
{
  return itkDynamicCastInDebugMode< const TInputImage * >( this->GetPrimaryInput() );
}

template< typename TInputImage >
vtkStructuredGrid *
SpecialCoordinatesImageToVTKStructuredGridFilter< TInputImage >
::GetOutput()
{
  return this->m_StructuredGrid.GetPointer();
}

template< typename TInputImage >
void
SpecialCoordinatesImageToVTKStructuredGridFilter< TInputImage >
::GenerateData()
{
  this->m_StructuredGrid->PrepareForNewData();
  // Const-cast because there is not (yet) a const version of GetBufferPointer()
  InputImageType * inputImage = const_cast< InputImageType * >( this->GetInput() );

  const typename InputImageType::RegionType region = inputImage->GetBufferedRegion();
  const typename InputImageType::SizeType size = region.GetSize();
  int dims[3];
  dims[2] = 1;
  for( unsigned int ii = 0; ii < ImageDimension; ++ii )
    {
    dims[ii] = size[ii];
    }
  this->m_StructuredGrid->SetDimensions( dims );

  vtkNew< vtkPoints > gridPoints;
  gridPoints->SetDataTypeToDouble();
  gridPoints->SetNumberOfPoints( region.GetNumberOfPixels() );

  ImageRegionConstIteratorWithIndex< InputImageType > imageIt( inputImage, region );
  imageIt.GoToBegin();
  for( SizeValueType ii = 0; !imageIt.IsAtEnd(); ++imageIt, ++ii )
    {
    const typename InputImageType::IndexType & index = imageIt.GetIndex();
    typename InputImageType::PointType point;
    inputImage->TransformIndexToPhysicalPoint( index, point );
    gridPoints->SetPoint( ii, point.GetVnlVector().data_block() );
    }

  vtkDataArray * pointDataArray;
  typedef typename InputImageType::PixelType           PixelType;
  typedef typename PixelTraits< PixelType >::ValueType ScalarType;
  const unsigned int components = inputImage->GetNumberOfComponentsPerPixel();
  const SizeValueType tuples = region.GetNumberOfPixels();
  if ( typeid( ScalarType ) == typeid( double ) )
    {
    vtkDoubleArray * array = vtkDoubleArray::New();
    array->SetNumberOfComponents( components );
    array->SetNumberOfTuples( tuples );
    std::memcpy( array->GetVoidPointer( 0 ), reinterpret_cast< void * >( inputImage->GetPixelContainer()->GetBufferPointer() ), tuples * components * sizeof( double ) );
    pointDataArray = array;
    }
  else if ( typeid( ScalarType ) == typeid( float ) )
    {
    vtkFloatArray * array = vtkFloatArray::New();
    array->SetNumberOfComponents( components );
    array->SetNumberOfTuples( tuples );
    std::memcpy( array->GetVoidPointer( 0 ), reinterpret_cast< void * >( inputImage->GetPixelContainer()->GetBufferPointer() ), tuples * components * sizeof( float ) );
    pointDataArray = array;
    }
  else if ( typeid( ScalarType ) == typeid( long ) )
    {
    vtkLongArray * array = vtkLongArray::New();
    array->SetNumberOfComponents( components );
    array->SetNumberOfTuples( tuples );
    std::memcpy( array->GetVoidPointer( 0 ), reinterpret_cast< void * >( inputImage->GetPixelContainer()->GetBufferPointer() ), tuples * components * sizeof( long ) );
    pointDataArray = array;
    }
  else if ( typeid( ScalarType ) == typeid( unsigned long ) )
    {
    vtkUnsignedLongArray * array = vtkUnsignedLongArray::New();
    array->SetNumberOfComponents( components );
    array->SetNumberOfTuples( tuples );
    std::memcpy( array->GetVoidPointer( 0 ), reinterpret_cast< void * >( inputImage->GetPixelContainer()->GetBufferPointer() ), tuples * components * sizeof( unsigned long ) );
    pointDataArray = array;
    }
  else if ( typeid( ScalarType ) == typeid( int ) )
    {
    vtkIntArray * array = vtkIntArray::New();
    array->SetNumberOfComponents( components );
    array->SetNumberOfTuples( tuples );
    std::memcpy( array->GetVoidPointer( 0 ), reinterpret_cast< void * >( inputImage->GetPixelContainer()->GetBufferPointer() ), tuples * components * sizeof( int ) );
    pointDataArray = array;
    }
  else if ( typeid( ScalarType ) == typeid( unsigned int ) )
    {
    vtkUnsignedIntArray * array = vtkUnsignedIntArray::New();
    array->SetNumberOfComponents( components );
    array->SetNumberOfTuples( tuples );
    std::memcpy( array->GetVoidPointer( 0 ), reinterpret_cast< void * >( inputImage->GetPixelContainer()->GetBufferPointer() ), tuples * components * sizeof( unsigned int ) );
    pointDataArray = array;
    }
  else if ( typeid( ScalarType ) == typeid( short ) )
    {
    vtkShortArray * array = vtkShortArray::New();
    array->SetNumberOfComponents( components );
    array->SetNumberOfTuples( tuples );
    std::memcpy( array->GetVoidPointer( 0 ), reinterpret_cast< void * >( inputImage->GetPixelContainer()->GetBufferPointer() ), tuples * components * sizeof( short ) );
    pointDataArray = array;
    }
  else if ( typeid( ScalarType ) == typeid( unsigned short ) )
    {
    vtkUnsignedShortArray * array = vtkUnsignedShortArray::New();
    array->SetNumberOfComponents( components );
    array->SetNumberOfTuples( tuples );
    std::memcpy( array->GetVoidPointer( 0 ), reinterpret_cast< void * >( inputImage->GetPixelContainer()->GetBufferPointer() ), tuples * components * sizeof( unsigned short ) );
    pointDataArray = array;
    }
  else if ( typeid( ScalarType ) == typeid( unsigned char ) )
    {
    vtkUnsignedCharArray * array = vtkUnsignedCharArray::New();
    array->SetNumberOfComponents( components );
    array->SetNumberOfTuples( tuples );
    std::memcpy( array->GetVoidPointer( 0 ), reinterpret_cast< void * >( inputImage->GetPixelContainer()->GetBufferPointer() ), tuples * components * sizeof( unsigned char ) );
    pointDataArray = array;
    }
  else if ( typeid( ScalarType ) == typeid( signed char ) )
    {
    vtkSignedCharArray * array = vtkSignedCharArray::New();
    array->SetNumberOfComponents( components );
    array->SetNumberOfTuples( tuples );
    std::memcpy( array->GetVoidPointer( 0 ), reinterpret_cast< void * >( inputImage->GetPixelContainer()->GetBufferPointer() ), tuples * components * sizeof( signed char ) );
    pointDataArray = array;
    }
  else
    {
    itkExceptionMacro(<< "Type currently not supported");
    }

  if( components == 1 )
    {
    this->m_StructuredGrid->GetPointData()->SetScalars( pointDataArray );
    }
  else
    {
    this->m_StructuredGrid->GetPointData()->SetVectors( pointDataArray );
    }
  pointDataArray->Delete();

  this->m_StructuredGrid->SetPoints( gridPoints.GetPointer() );
}

} // end namespace itk

#endif
<commit_msg>ENH: Add progress reporting vtkStructuredGrid conversion<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/
#ifndef itkSpecialCoordinatesImageToVTKStructuredGridFilter_hxx
#define itkSpecialCoordinatesImageToVTKStructuredGridFilter_hxx

#include "itkSpecialCoordinatesImageToVTKStructuredGridFilter.h"

#include "itkImageRegionConstIteratorWithIndex.h"
#include "itkPixelTraits.h"
#include "itkProgressReporter.h"

#include "vtkPointData.h"
#include "vtkNew.h"
#include "vtkPoints.h"
#include "vtkDataArray.h"
#include "vtkDoubleArray.h"
#include "vtkFloatArray.h"
#include "vtkLongArray.h"
#include "vtkUnsignedLongArray.h"
#include "vtkIntArray.h"
#include "vtkUnsignedIntArray.h"
#include "vtkShortArray.h"
#include "vtkUnsignedShortArray.h"
#include "vtkUnsignedCharArray.h"
#include "vtkSignedCharArray.h"

#include <cstring>

namespace itk
{

template< typename TInputImage >
SpecialCoordinatesImageToVTKStructuredGridFilter< TInputImage >
::SpecialCoordinatesImageToVTKStructuredGridFilter()
{
  this->SetNumberOfRequiredInputs( 1 );

  this->SetPrimaryOutputName( "StructuredGrid" );
  this->SetNumberOfRequiredOutputs( 1 );
  this->ReleaseDataBeforeUpdateFlagOff();

  typename DecoratedStructuredGridPointerType::Pointer decoratedStructuredGrid =
        itkDynamicCastInDebugMode< DecoratedStructuredGridPointerType * >( this->MakeOutput(0).GetPointer() );
  decoratedStructuredGrid->Set( m_StructuredGrid );
  this->ProcessObject::SetNthOutput( 0, decoratedStructuredGrid );
}

template< typename TInputImage >
SpecialCoordinatesImageToVTKStructuredGridFilter< TInputImage >
::~SpecialCoordinatesImageToVTKStructuredGridFilter()
{
}

template< typename TInputImage >
DataObject::Pointer
SpecialCoordinatesImageToVTKStructuredGridFilter< TInputImage >
::MakeOutput( DataObjectPointerArraySizeType output )
{
  switch ( output )
    {
    case 0:
      {
      m_StructuredGrid = vtkSmartPointer< vtkStructuredGrid >::New();
      DecoratedStructuredGridPointerType::Pointer decoratedStructuredGrid = DecoratedStructuredGridPointerType::New();
      decoratedStructuredGrid->Set( m_StructuredGrid );
      return decoratedStructuredGrid.GetPointer();
      }
    default:
      itkExceptionMacro( "MakeOutput request for an output number larger than the expected number of outputs." );
      return ITK_NULLPTR;
    }
}

template< typename TInputImage >
void
SpecialCoordinatesImageToVTKStructuredGridFilter< TInputImage >
::SetInput(const InputImageType *input)
{
  // Process object is not const-correct so the const_cast is required here
  this->ProcessObject::SetNthInput( 0, const_cast< InputImageType * >( input ) );
}

template< typename TInputImage >
const typename SpecialCoordinatesImageToVTKStructuredGridFilter< TInputImage >::InputImageType *
SpecialCoordinatesImageToVTKStructuredGridFilter< TInputImage >
::GetInput() const
{
  return itkDynamicCastInDebugMode< const TInputImage * >( this->GetPrimaryInput() );
}

template< typename TInputImage >
vtkStructuredGrid *
SpecialCoordinatesImageToVTKStructuredGridFilter< TInputImage >
::GetOutput()
{
  return this->m_StructuredGrid.GetPointer();
}

template< typename TInputImage >
void
SpecialCoordinatesImageToVTKStructuredGridFilter< TInputImage >
::GenerateData()
{
  this->m_StructuredGrid->PrepareForNewData();
  // Const-cast because there is not (yet) a const version of GetBufferPointer()
  InputImageType * inputImage = const_cast< InputImageType * >( this->GetInput() );

  const typename InputImageType::RegionType region = inputImage->GetBufferedRegion();
  const typename InputImageType::SizeType size = region.GetSize();
  int dims[3];
  dims[2] = 1;
  for( unsigned int ii = 0; ii < ImageDimension; ++ii )
    {
    dims[ii] = size[ii];
    }
  this->m_StructuredGrid->SetDimensions( dims );

  vtkNew< vtkPoints > gridPoints;
  gridPoints->SetDataTypeToDouble();
  gridPoints->SetNumberOfPoints( region.GetNumberOfPixels() );

  ProgressReporter progress( this, 0, region.GetNumberOfPixels() );

  ImageRegionConstIteratorWithIndex< InputImageType > imageIt( inputImage, region );
  imageIt.GoToBegin();
  for( SizeValueType ii = 0; !imageIt.IsAtEnd(); ++imageIt, ++ii )
    {
    const typename InputImageType::IndexType & index = imageIt.GetIndex();
    typename InputImageType::PointType point;
    inputImage->TransformIndexToPhysicalPoint( index, point );
    gridPoints->SetPoint( ii, point.GetVnlVector().data_block() );
    progress.CompletedPixel();
    }

  vtkDataArray * pointDataArray;
  typedef typename InputImageType::PixelType           PixelType;
  typedef typename PixelTraits< PixelType >::ValueType ScalarType;
  const unsigned int components = inputImage->GetNumberOfComponentsPerPixel();
  const SizeValueType tuples = region.GetNumberOfPixels();
  if ( typeid( ScalarType ) == typeid( double ) )
    {
    vtkDoubleArray * array = vtkDoubleArray::New();
    array->SetNumberOfComponents( components );
    array->SetNumberOfTuples( tuples );
    std::memcpy( array->GetVoidPointer( 0 ), reinterpret_cast< void * >( inputImage->GetPixelContainer()->GetBufferPointer() ), tuples * components * sizeof( double ) );
    pointDataArray = array;
    }
  else if ( typeid( ScalarType ) == typeid( float ) )
    {
    vtkFloatArray * array = vtkFloatArray::New();
    array->SetNumberOfComponents( components );
    array->SetNumberOfTuples( tuples );
    std::memcpy( array->GetVoidPointer( 0 ), reinterpret_cast< void * >( inputImage->GetPixelContainer()->GetBufferPointer() ), tuples * components * sizeof( float ) );
    pointDataArray = array;
    }
  else if ( typeid( ScalarType ) == typeid( long ) )
    {
    vtkLongArray * array = vtkLongArray::New();
    array->SetNumberOfComponents( components );
    array->SetNumberOfTuples( tuples );
    std::memcpy( array->GetVoidPointer( 0 ), reinterpret_cast< void * >( inputImage->GetPixelContainer()->GetBufferPointer() ), tuples * components * sizeof( long ) );
    pointDataArray = array;
    }
  else if ( typeid( ScalarType ) == typeid( unsigned long ) )
    {
    vtkUnsignedLongArray * array = vtkUnsignedLongArray::New();
    array->SetNumberOfComponents( components );
    array->SetNumberOfTuples( tuples );
    std::memcpy( array->GetVoidPointer( 0 ), reinterpret_cast< void * >( inputImage->GetPixelContainer()->GetBufferPointer() ), tuples * components * sizeof( unsigned long ) );
    pointDataArray = array;
    }
  else if ( typeid( ScalarType ) == typeid( int ) )
    {
    vtkIntArray * array = vtkIntArray::New();
    array->SetNumberOfComponents( components );
    array->SetNumberOfTuples( tuples );
    std::memcpy( array->GetVoidPointer( 0 ), reinterpret_cast< void * >( inputImage->GetPixelContainer()->GetBufferPointer() ), tuples * components * sizeof( int ) );
    pointDataArray = array;
    }
  else if ( typeid( ScalarType ) == typeid( unsigned int ) )
    {
    vtkUnsignedIntArray * array = vtkUnsignedIntArray::New();
    array->SetNumberOfComponents( components );
    array->SetNumberOfTuples( tuples );
    std::memcpy( array->GetVoidPointer( 0 ), reinterpret_cast< void * >( inputImage->GetPixelContainer()->GetBufferPointer() ), tuples * components * sizeof( unsigned int ) );
    pointDataArray = array;
    }
  else if ( typeid( ScalarType ) == typeid( short ) )
    {
    vtkShortArray * array = vtkShortArray::New();
    array->SetNumberOfComponents( components );
    array->SetNumberOfTuples( tuples );
    std::memcpy( array->GetVoidPointer( 0 ), reinterpret_cast< void * >( inputImage->GetPixelContainer()->GetBufferPointer() ), tuples * components * sizeof( short ) );
    pointDataArray = array;
    }
  else if ( typeid( ScalarType ) == typeid( unsigned short ) )
    {
    vtkUnsignedShortArray * array = vtkUnsignedShortArray::New();
    array->SetNumberOfComponents( components );
    array->SetNumberOfTuples( tuples );
    std::memcpy( array->GetVoidPointer( 0 ), reinterpret_cast< void * >( inputImage->GetPixelContainer()->GetBufferPointer() ), tuples * components * sizeof( unsigned short ) );
    pointDataArray = array;
    }
  else if ( typeid( ScalarType ) == typeid( unsigned char ) )
    {
    vtkUnsignedCharArray * array = vtkUnsignedCharArray::New();
    array->SetNumberOfComponents( components );
    array->SetNumberOfTuples( tuples );
    std::memcpy( array->GetVoidPointer( 0 ), reinterpret_cast< void * >( inputImage->GetPixelContainer()->GetBufferPointer() ), tuples * components * sizeof( unsigned char ) );
    pointDataArray = array;
    }
  else if ( typeid( ScalarType ) == typeid( signed char ) )
    {
    vtkSignedCharArray * array = vtkSignedCharArray::New();
    array->SetNumberOfComponents( components );
    array->SetNumberOfTuples( tuples );
    std::memcpy( array->GetVoidPointer( 0 ), reinterpret_cast< void * >( inputImage->GetPixelContainer()->GetBufferPointer() ), tuples * components * sizeof( signed char ) );
    pointDataArray = array;
    }
  else
    {
    itkExceptionMacro(<< "Type currently not supported");
    }

  if( components == 1 )
    {
    this->m_StructuredGrid->GetPointData()->SetScalars( pointDataArray );
    }
  else
    {
    this->m_StructuredGrid->GetPointData()->SetVectors( pointDataArray );
    }
  pointDataArray->Delete();

  this->m_StructuredGrid->SetPoints( gridPoints.GetPointer() );
}

} // end namespace itk

#endif
<|endoftext|>