<commit_before>#include <iostream>
#include <fstream>
#include <OpenNI.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/io/Grabber.h>
#include <pcl/point_cloud.h>
#include <pcl/io/openni2_grabber.h>
#include <pcl/console/print.h>
#include <pcl/io/pcd_grabber.h>
#include <pcl/console/parse.h>
#include <pcl/visualization/boost.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/visualization/image_viewer.h>
#include <vector>
#include "onimeshfunctions.h"

namespace onimesh
{

    boost::mutex mutex_;
    boost::shared_ptr<pcl::PCDGrabber<pcl::PointXYZRGBA> > grabber;
    pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr cloud_;

    typedef pcl::PointCloud<pcl::PointXYZRGBA> Cloud;
    typedef Cloud::ConstPtr CloudConstPtr;

    int i = 0;
    char buf[4096];

	const int FRAME_DATA_MOD = 100;

	/// <summary>
	/// Creates a name for an output file
	/// </summary>
	std::string getOutputFileName(const char* outputDirectory, const char* inputFile, const char* fileExtension)
	{
		// If the path contains '/' characters
		if (std::string(inputFile).find_last_of('/') != std::string::npos)
		{
			// Check if the directory needs a trailing '/'
			if (std::string(outputDirectory).back() == '/' || std::string(outputDirectory).back() == '\\')
				return std::string(std::string(outputDirectory) + std::string(inputFile).substr(std::string(inputFile).find_last_of('/') + 1) + std::string(fileExtension));

			return std::string(std::string(outputDirectory) + std::string("/") + std::string(inputFile).substr(std::string(inputFile).find_last_of('/') + 1) + std::string(fileExtension));
		}
		// If the path contains '\' characters
		else if (std::string(inputFile).find_last_of('\\') == std::string::npos)
		{
			// Check if the directory needs a trailing '\'
			if (std::string(outputDirectory).back() == '/' || std::string(outputDirectory).back() == '\\')
				return std::string(std::string(outputDirectory) + std::string(inputFile).substr(std::string(inputFile).find_last_of('\\') + 1) + std::string(fileExtension));

			return std::string(std::string(outputDirectory) + std::string("\\") + std::string(inputFile).substr(std::string(inputFile).find_last_of('\\') + 1) + std::string(fileExtension));
		}

		// Otherwise the input file does not contain a path
		// Check if the directory needs a trailing '/'
		if (std::string(outputDirectory).back() == '/' || std::string(outputDirectory).back() == '\\')
			return std::string(std::string(outputDirectory) + std::string(inputFile) + std::string(fileExtension));

		return std::string(std::string(outputDirectory) + std::string("/") + std::string(inputFile) + std::string(fileExtension));
	}

	/// <summary>
	/// Reads oni input and exports data as excel docs
	/// </summary>
	void outputExcel(const int argc, const char** argv)
	{
		std::cout << "Start excel data output...\n";

        const char* outputDirectory = argv[1];
        char* inputFile;
		const int numberInputFiles = argc - 2;
		openni::Device device;
		openni::VideoStream ir;
		openni::VideoFrameRef irf;
		OniDepthPixel* pDepth;
		int frameHeight, frameWidth;
		long frameIndex, numberOfFrames;
		std::ofstream out;

        // Initialize openni
        openni::Status rc = openni::OpenNI::initialize();
        if (rc != openni::STATUS_OK)
        {
            printf("Initialize failed\n%s\n", openni::OpenNI::getExtendedError());
            exit(2);
        }

		// Output excel doc for each input file
		for (int w = 0; w < numberInputFiles; ++w)
		{
			inputFile = (char*)argv[w + 2];
			std::cout << "Working on file " << inputFile << "...\n";

			// Open the .oni file
			rc = device.open(inputFile);
            if (rc != openni::STATUS_OK)
            {
                printf("Couldn't open device\n%s\n", openni::OpenNI::getExtendedError());
                exit(3);
            }

            // Create the Video Stream
			rc = ir.create(device, openni::SENSOR_DEPTH);
            if (rc != openni::STATUS_OK)
            {
                printf("Couldn't create depth stream\n%s\n", openni::OpenNI::getExtendedError());
                exit(4);
            }

			// Device Check
			if (!device.isValid())
			{
				std::cerr << "\nThe device is not valid.\n";
				exit(5);
			}

			// Verify the device is a file
			if (!device.isFile())
			{
				std::cerr << "\nThe device is not a file.\n";
				exit(6);
			}
			std::cout << "File open success...\n";

			// Set playback controls
			openni::PlaybackControl* pbc = device.getPlaybackControl();
			pbc->setSpeed(-1);
			pbc->setRepeatEnabled(false);

			// Open output file
			std::string outputFile = getOutputFileName(outputDirectory, inputFile, ".csv");
			out.open(outputFile);

			// Read all frames
			numberOfFrames = pbc->getNumberOfFrames(ir);
			std::cout << "Start reading frame data...\n";
			rc = ir.start();
            if (rc != openni::STATUS_OK)
            {
                printf("Couldn't start the depth stream\n%s\n", openni::OpenNI::getExtendedError());
                exit(7);
            }

			while (true)
			{
				// Read a frame
				rc = ir.readFrame(&irf);
                if (rc != openni::STATUS_OK)
                {
                    printf("Read failed!\n%s\n", openni::OpenNI::getExtendedError());
                    continue;
                }

				// Verify frame data is valid
				if (!irf.isValid())
				{
					std::cerr << "Error reading video stream frame\n";
					break;
				}

				// Gather frame data
				pDepth = (OniDepthPixel*)irf.getData();
				frameIndex = irf.getFrameIndex();

				// Skip unneeded frames
				if (frameIndex % FRAME_DATA_MOD == 0)
				{
					frameHeight = irf.getHeight();
					frameWidth = irf.getWidth();
					std::cout << "Processing " << frameWidth << "x" << frameHeight << " frame number " << frameIndex << "...\n";
					out << "FrameNumber=" << frameIndex << ",FrameWidth=" << frameWidth << ",FrameHeight=" << frameHeight << ",\n";
					for (int y = 0; y < frameHeight; ++y)  // All heights
					{
						for (int x = 0; x < frameWidth; ++x, ++pDepth)  // All witdths
						{
							out << *pDepth << ",";
						}
						out << "\n";
					}
					out << ",\n";
				}
				else
				{
					//std::cout << "Skipping frame " << frameIndex << "\n";
				}

				// Break if reading the last frame
				if (numberOfFrames == frameIndex)
				{
					std::cout << "Last frame has been read...\n";
					break;
				}
			}

			// Cleanup
			out.clear();
			out.close();
			ir.stop();
			ir.destroy();
			device.close();
		}

		// OpenNI cleanup
		openni::OpenNI::shutdown();
		std::cout << "Excel data output complete.\n";
	}

	/// <summary>
	/// Reads oni input and exports data as point clouds
	/// </summary>
    /*
     * Software License Agreement (BSD License)
     *
     *  Point Cloud Library (PCL) - www.pointclouds.org
     *  Copyright (c) 2011, Willow Garage, Inc.
     *  Copyright (c) 2012-, Open Perception, Inc.
     *
     *  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 copyright holder(s) 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
     *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
     *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
     *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
     *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     *  POSSIBILITY OF SUCH DAMAGE.
     *
     *
     */

    //////////////////////////////////////////////////////////////////////////////
	//cloud_cb
	//Purpose: Takes a cloud object and writes it to a PCD file.
	//////////////////////////////////////////////////////////////////////////////
    void cloud_cb (const CloudConstPtr& cloud)
    {
        pcl::PCDWriter w;
        sprintf_s (buf, "frame_%06d.pcd", i);
        w.writeBinaryCompressed (buf, *cloud);
        PCL_INFO ("Wrote a cloud with %lu (%ux%u) points in %s.\n",
                  cloud->size (), cloud->width, cloud->height, buf);
        ++i;
    }

    ////////////////////////////////////////////////////////////////////////////////////////////
	// outputPointCloud
	// Purpose: Makes a OpenNI2Grabber to read from the ONI file. As the file is read in cloud_cb
	//          is called to write the data to a PCD file. After the file has been read the
	//			grabber is deleted.
	///////////////////////////////////////////////////////////////////////////////////////////
	void outputPointCloud(const int argc, const char** argv)
	{
		//Writes a message to the console.
        pcl::console::print_info ("Convert an ONI file to PCD format.\n");

        //Initializes a grabber for the ONI file.
        pcl::io::OpenNI2Grabber* grabber = new pcl::io::OpenNI2Grabber (argv[2]);
		//Calls boost to set up writing to PCD
        boost::function<void (const CloudConstPtr&) > f = boost::bind (&cloud_cb, _1);
		//Callback to let the program know when the file has been written.
        boost::signals2::connection c = grabber->registerCallback (f);

		//Do-while loop to read in all of the frames from the ONI file
        do
        {
            grabber->start ();
        }while (grabber->isRunning ());

        PCL_INFO ("Successfully processed %d frames.\n", i);

        delete grabber;
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////
    //This is the area for using the pointCloudViewer

    /// <summary>
	/// This is a dummy example to show the use of writing a pcl file
	/// that contains a 5x2 cloud with random values
	/// Code taken from here:
	/// http://pointclouds.org/documentation/tutorials/writing_pcd.php#writing-pcd
	/// </summary>
	void createDummyPointCloud()
	{
		pcl::PointCloud<pcl::PointXYZ> cloud;

		// Fill in the cloud data
		cloud.width = 5;
		cloud.height = 2;
		cloud.is_dense = false;
		cloud.points.resize(cloud.width * cloud.height);

		for (size_t i = 0; i < cloud.points.size(); ++i)
		{
			cloud.points[i].x = 1024 * rand() / (RAND_MAX + 1.0f);
			cloud.points[i].y = 1024 * rand() / (RAND_MAX + 1.0f);
			cloud.points[i].z = 1024 * rand() / (RAND_MAX + 1.0f);
		}

		pcl::io::savePCDFileASCII("test_pcd.pcd", cloud);
		std::cerr << "Saved " << cloud.points.size() << " data points to test_pcd.pcd." << std::endl;

		for (size_t i = 0; i < cloud.points.size(); ++i)
			std::cerr << "    " << cloud.points[i].x << " " << cloud.points[i].y << " " << cloud.points[i].z << std::endl;
	}
}<commit_msg>added modulus functionality for point cloud<commit_after>#include <iostream>
#include <fstream>
#include <OpenNI.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/io/Grabber.h>
#include <pcl/point_cloud.h>
#include <pcl/io/openni2_grabber.h>
#include <pcl/console/print.h>
#include <pcl/io/pcd_grabber.h>
#include <pcl/console/parse.h>
#include <pcl/visualization/boost.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/visualization/image_viewer.h>
#include <vector>
#include "onimeshfunctions.h"

namespace onimesh
{

    boost::mutex mutex_;
    boost::shared_ptr<pcl::PCDGrabber<pcl::PointXYZRGBA> > grabber;
    pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr cloud_;

    typedef pcl::PointCloud<pcl::PointXYZRGBA> Cloud;
    typedef Cloud::ConstPtr CloudConstPtr;

    int i = 0;
    char buf[4096];

	const int FRAME_DATA_MOD = 100;

	/// <summary>
	/// Creates a name for an output file
	/// </summary>
	std::string getOutputFileName(const char* outputDirectory, const char* inputFile, const char* fileExtension)
	{
		// If the path contains '/' characters
		if (std::string(inputFile).find_last_of('/') != std::string::npos)
		{
			// Check if the directory needs a trailing '/'
			if (std::string(outputDirectory).back() == '/' || std::string(outputDirectory).back() == '\\')
				return std::string(std::string(outputDirectory) + std::string(inputFile).substr(std::string(inputFile).find_last_of('/') + 1) + std::string(fileExtension));

			return std::string(std::string(outputDirectory) + std::string("/") + std::string(inputFile).substr(std::string(inputFile).find_last_of('/') + 1) + std::string(fileExtension));
		}
		// If the path contains '\' characters
		else if (std::string(inputFile).find_last_of('\\') == std::string::npos)
		{
			// Check if the directory needs a trailing '\'
			if (std::string(outputDirectory).back() == '/' || std::string(outputDirectory).back() == '\\')
				return std::string(std::string(outputDirectory) + std::string(inputFile).substr(std::string(inputFile).find_last_of('\\') + 1) + std::string(fileExtension));

			return std::string(std::string(outputDirectory) + std::string("\\") + std::string(inputFile).substr(std::string(inputFile).find_last_of('\\') + 1) + std::string(fileExtension));
		}

		// Otherwise the input file does not contain a path
		// Check if the directory needs a trailing '/'
		if (std::string(outputDirectory).back() == '/' || std::string(outputDirectory).back() == '\\')
			return std::string(std::string(outputDirectory) + std::string(inputFile) + std::string(fileExtension));

		return std::string(std::string(outputDirectory) + std::string("/") + std::string(inputFile) + std::string(fileExtension));
	}

	/// <summary>
	/// Reads oni input and exports data as excel docs
	/// </summary>
	void outputExcel(const int argc, const char** argv)
	{
		std::cout << "Start excel data output...\n";

        const char* outputDirectory = argv[1];
        char* inputFile;
		const int numberInputFiles = argc - 2;
		openni::Device device;
		openni::VideoStream ir;
		openni::VideoFrameRef irf;
		OniDepthPixel* pDepth;
		int frameHeight, frameWidth;
		long frameIndex, numberOfFrames;
		std::ofstream out;

        // Initialize openni
        openni::Status rc = openni::OpenNI::initialize();
        if (rc != openni::STATUS_OK)
        {
            printf("Initialize failed\n%s\n", openni::OpenNI::getExtendedError());
            exit(2);
        }

		// Output excel doc for each input file
		for (int w = 0; w < numberInputFiles; ++w)
		{
			inputFile = (char*)argv[w + 2];
			std::cout << "Working on file " << inputFile << "...\n";

			// Open the .oni file
			rc = device.open(inputFile);
            if (rc != openni::STATUS_OK)
            {
                printf("Couldn't open device\n%s\n", openni::OpenNI::getExtendedError());
                exit(3);
            }

            // Create the Video Stream
			rc = ir.create(device, openni::SENSOR_DEPTH);
            if (rc != openni::STATUS_OK)
            {
                printf("Couldn't create depth stream\n%s\n", openni::OpenNI::getExtendedError());
                exit(4);
            }

			// Device Check
			if (!device.isValid())
			{
				std::cerr << "\nThe device is not valid.\n";
				exit(5);
			}

			// Verify the device is a file
			if (!device.isFile())
			{
				std::cerr << "\nThe device is not a file.\n";
				exit(6);
			}
			std::cout << "File open success...\n";

			// Set playback controls
			openni::PlaybackControl* pbc = device.getPlaybackControl();
			pbc->setSpeed(-1);
			pbc->setRepeatEnabled(false);

			// Open output file
			std::string outputFile = getOutputFileName(outputDirectory, inputFile, ".csv");
			out.open(outputFile);

			// Read all frames
			numberOfFrames = pbc->getNumberOfFrames(ir);
			std::cout << "Start reading frame data...\n";
			rc = ir.start();
            if (rc != openni::STATUS_OK)
            {
                printf("Couldn't start the depth stream\n%s\n", openni::OpenNI::getExtendedError());
                exit(7);
            }

			while (true)
			{
				// Read a frame
				rc = ir.readFrame(&irf);
                if (rc != openni::STATUS_OK)
                {
                    printf("Read failed!\n%s\n", openni::OpenNI::getExtendedError());
                    continue;
                }

				// Verify frame data is valid
				if (!irf.isValid())
				{
					std::cerr << "Error reading video stream frame\n";
					break;
				}

				// Gather frame data
				pDepth = (OniDepthPixel*)irf.getData();
				frameIndex = irf.getFrameIndex();

				// Skip unneeded frames
				if (frameIndex % FRAME_DATA_MOD == 0)
				{
					frameHeight = irf.getHeight();
					frameWidth = irf.getWidth();
					std::cout << "Processing " << frameWidth << "x" << frameHeight << " frame number " << frameIndex << "...\n";
					out << "FrameNumber=" << frameIndex << ",FrameWidth=" << frameWidth << ",FrameHeight=" << frameHeight << ",\n";
					for (int y = 0; y < frameHeight; ++y)  // All heights
					{
						for (int x = 0; x < frameWidth; ++x, ++pDepth)  // All witdths
						{
							out << *pDepth << ",";
						}
						out << "\n";
					}
					out << ",\n";
				}
				else
				{
					//std::cout << "Skipping frame " << frameIndex << "\n";
				}

				// Break if reading the last frame
				if (numberOfFrames == frameIndex)
				{
					std::cout << "Last frame has been read...\n";
					break;
				}
			}

			// Cleanup
			out.clear();
			out.close();
			ir.stop();
			ir.destroy();
			device.close();
		}

		// OpenNI cleanup
		openni::OpenNI::shutdown();
		std::cout << "Excel data output complete.\n";
	}

	/// <summary>
	/// Reads oni input and exports data as point clouds
	/// </summary>
    /*
     * Software License Agreement (BSD License)
     *
     *  Point Cloud Library (PCL) - www.pointclouds.org
     *  Copyright (c) 2011, Willow Garage, Inc.
     *  Copyright (c) 2012-, Open Perception, Inc.
     *
     *  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 copyright holder(s) 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
     *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
     *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
     *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
     *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     *  POSSIBILITY OF SUCH DAMAGE.
     *
     *
     */

    //////////////////////////////////////////////////////////////////////////////
	//cloud_cb
	//Purpose: Takes a cloud object and writes it to a PCD file.
	//////////////////////////////////////////////////////////////////////////////
    void cloud_cb (const CloudConstPtr& cloud)
    {
        if ( i % 50 == 0)
        {
            pcl::PCDWriter w;
            sprintf_s (buf, "frame_%06d.pcd", i);
            w.writeBinaryCompressed (buf, *cloud);
            PCL_INFO ("Wrote a cloud with %lu (%ux%u) points in %s.\n",
                  cloud->size (), cloud->width, cloud->height, buf);
        }
        ++i;
    }

    ////////////////////////////////////////////////////////////////////////////////////////////
	// outputPointCloud
	// Purpose: Makes a OpenNI2Grabber to read from the ONI file. As the file is read in cloud_cb
	//          is called to write the data to a PCD file. After the file has been read the
	//			grabber is deleted.
	///////////////////////////////////////////////////////////////////////////////////////////
	void outputPointCloud(const int argc, const char** argv)
	{
        for (int j = 2; j < argc; j++)
        {
            //Writes a message to the console.
            pcl::console::print_info ("Convert an ONI file to PCD format.\n");

            //Initializes a grabber for the ONI file.
            pcl::io::OpenNI2Grabber* grabber = new pcl::io::OpenNI2Grabber (argv[j]);
            //Calls boost to set up writing to PCD
            boost::function<void (const CloudConstPtr&) > f = boost::bind (&cloud_cb, _1);
            //Callback to let the program know when the file has been written.
            boost::signals2::connection c = grabber->registerCallback (f);

            //Do-while loop to read in all of the frames from the ONI file
            do
            {
                grabber->start ();
            }while (grabber->isRunning ());

            PCL_INFO ("Successfully processed %d frames.\n", i);

            delete grabber;
        }
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////
    //This is the area for using the pointCloudViewer

    /// <summary>
	/// This is a dummy example to show the use of writing a pcl file
	/// that contains a 5x2 cloud with random values
	/// Code taken from here:
	/// http://pointclouds.org/documentation/tutorials/writing_pcd.php#writing-pcd
	/// </summary>
	void createDummyPointCloud()
	{
		pcl::PointCloud<pcl::PointXYZ> cloud;

		// Fill in the cloud data
		cloud.width = 5;
		cloud.height = 2;
		cloud.is_dense = false;
		cloud.points.resize(cloud.width * cloud.height);

		for (size_t i = 0; i < cloud.points.size(); ++i)
		{
			cloud.points[i].x = 1024 * rand() / (RAND_MAX + 1.0f);
			cloud.points[i].y = 1024 * rand() / (RAND_MAX + 1.0f);
			cloud.points[i].z = 1024 * rand() / (RAND_MAX + 1.0f);
		}

		pcl::io::savePCDFileASCII("test_pcd.pcd", cloud);
		std::cerr << "Saved " << cloud.points.size() << " data points to test_pcd.pcd." << std::endl;

		for (size_t i = 0; i < cloud.points.size(); ++i)
			std::cerr << "    " << cloud.points[i].x << " " << cloud.points[i].y << " " << cloud.points[i].z << std::endl;
	}
}<|endoftext|>


<commit_before>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  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.
 */
/*
 * Copyright (C) 2016 ScyllaDB
 */

#include "prometheus.hh"
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include "proto/metrics2.pb.h"

#include "scollectd_api.hh"
#include "http/function_handlers.hh"
#include <boost/algorithm/string/replace.hpp>

namespace prometheus {
namespace pm = io::prometheus::client;

/**
 * Taken from an answer in stackoverflow:
 * http://stackoverflow.com/questions/2340730/are-there-c-equivalents-for-the-protocol-buffers-delimited-i-o-functions-in-ja
 */
static bool write_delimited_to(const google::protobuf::MessageLite& message,
        google::protobuf::io::ZeroCopyOutputStream* rawOutput) {
    google::protobuf::io::CodedOutputStream output(rawOutput);

    const int size = message.ByteSize();
    output.WriteVarint32(size);

    uint8_t* buffer = output.GetDirectBufferForNBytesAndAdvance(size);
    if (buffer != nullptr) {
        message.SerializeWithCachedSizesToArray(buffer);
    } else {
        message.SerializeWithCachedSizes(&output);
        if (output.HadError()) {
            return false;
        }
    }

    return true;
}

static std::string safe_name(const sstring& name) {
    return boost::replace_all_copy(boost::replace_all_copy(name, "-", "_"), " ", "_");
}

static sstring collectd_name(const scollectd::type_instance_id & id, uint32_t cpu) {
    return safe_name(id.plugin()) + ":" + safe_name(id.type()) + ":" + safe_name(id.type_instance()) + ":" + std::to_string(cpu);
}

static void fill_metric(pm::MetricFamily& mf, const std::vector<scollectd::collectd_value>& vals) {
    for (const scollectd::collectd_value& c : vals) {
        switch (c.type()) {
        case scollectd::data_type::DERIVE:
            mf.add_metric()->mutable_counter()->set_value(c.i());
            mf.set_type(pm::MetricType::COUNTER);
            break;
        case scollectd::data_type::GAUGE:
            mf.add_metric()->mutable_gauge()->set_value(c.d());
            mf.set_type(pm::MetricType::GAUGE);
            break;
        default:
            mf.add_metric()->mutable_counter()->set_value(c.ui());
            mf.set_type(pm::MetricType::COUNTER);
            break;
        }
    }
}

future<> start(httpd::http_server_control& http_server, const config& ctx) {
    return http_server.set_routes([&ctx](httpd::routes& r) {
        httpd::future_handler_function f = [&ctx](std::unique_ptr<request> req, std::unique_ptr<reply> rep) {
            return do_with(std::vector<scollectd::value_map>(), [rep = std::move(rep), &ctx] (auto& vec) mutable {
                vec.resize(smp::count);
                return parallel_for_each(boost::irange(0u, smp::count), [&vec] (auto cpu) {
                    return smp::submit_to(cpu, [] {
                        return scollectd::get_value_map();
                    }).then([&vec, cpu] (auto res) {
                        vec[cpu] = res;
                    });
                }).then([rep = std::move(rep), &vec, &ctx]() mutable {
                    uint32_t cpu = 0;
                    for (auto value: vec) {
                        cpu++;
                        for (auto i : value) {
                            pm::MetricFamily mtf;
                            std::string s;
                            google::protobuf::io::StringOutputStream os(&s);
                            mtf.set_name(collectd_name(i.first, cpu));
                            mtf.set_help(ctx.metric_help);
                            fill_metric(mtf, i.second);
                            if (mtf.metric_size() > 0) {
                                std::stringstream ss;
                                if (!write_delimited_to(mtf, &os)) {
                                    seastar_logger.warn("Failed to write protobuf metrics");
                                }
                                rep->_content += s;
                            }
                        }
                    }
                    return make_ready_future<std::unique_ptr<reply>>(std::move(rep));
                });
            });
        };
        r.put(GET, "/metrics", new httpd::function_handler(f, "proto"));
    });
}

}
<commit_msg>prometheus: remove invalid chars from meric names<commit_after>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  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.
 */
/*
 * Copyright (C) 2016 ScyllaDB
 */

#include "prometheus.hh"
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include "proto/metrics2.pb.h"

#include "scollectd_api.hh"
#include "http/function_handlers.hh"
#include <boost/algorithm/string/replace.hpp>
#include <boost/range/algorithm_ext/erase.hpp>
#include <boost/algorithm/string.hpp>

namespace prometheus {
namespace pm = io::prometheus::client;

/**
 * Taken from an answer in stackoverflow:
 * http://stackoverflow.com/questions/2340730/are-there-c-equivalents-for-the-protocol-buffers-delimited-i-o-functions-in-ja
 */
static bool write_delimited_to(const google::protobuf::MessageLite& message,
        google::protobuf::io::ZeroCopyOutputStream* rawOutput) {
    google::protobuf::io::CodedOutputStream output(rawOutput);

    const int size = message.ByteSize();
    output.WriteVarint32(size);

    uint8_t* buffer = output.GetDirectBufferForNBytesAndAdvance(size);
    if (buffer != nullptr) {
        message.SerializeWithCachedSizesToArray(buffer);
    } else {
        message.SerializeWithCachedSizes(&output);
        if (output.HadError()) {
            return false;
        }
    }

    return true;
}

static std::string safe_name(const sstring& name) {
    auto rep = boost::replace_all_copy(boost::replace_all_copy(name, "-", "_"), " ", "_");
    boost::remove_erase_if(rep, boost::is_any_of("+()"));
    return rep;
}

static sstring collectd_name(const scollectd::type_instance_id & id, uint32_t cpu) {
    return safe_name(id.plugin()) + ":" + safe_name(id.type()) + ":" + safe_name(id.type_instance()) + ":" + std::to_string(cpu);
}

static void fill_metric(pm::MetricFamily& mf, const std::vector<scollectd::collectd_value>& vals) {
    for (const scollectd::collectd_value& c : vals) {
        switch (c.type()) {
        case scollectd::data_type::DERIVE:
            mf.add_metric()->mutable_counter()->set_value(c.i());
            mf.set_type(pm::MetricType::COUNTER);
            break;
        case scollectd::data_type::GAUGE:
            mf.add_metric()->mutable_gauge()->set_value(c.d());
            mf.set_type(pm::MetricType::GAUGE);
            break;
        default:
            mf.add_metric()->mutable_counter()->set_value(c.ui());
            mf.set_type(pm::MetricType::COUNTER);
            break;
        }
    }
}

future<> start(httpd::http_server_control& http_server, const config& ctx) {
    return http_server.set_routes([&ctx](httpd::routes& r) {
        httpd::future_handler_function f = [&ctx](std::unique_ptr<request> req, std::unique_ptr<reply> rep) {
            return do_with(std::vector<scollectd::value_map>(), [rep = std::move(rep), &ctx] (auto& vec) mutable {
                vec.resize(smp::count);
                return parallel_for_each(boost::irange(0u, smp::count), [&vec] (auto cpu) {
                    return smp::submit_to(cpu, [] {
                        return scollectd::get_value_map();
                    }).then([&vec, cpu] (auto res) {
                        vec[cpu] = res;
                    });
                }).then([rep = std::move(rep), &vec, &ctx]() mutable {
                    uint32_t cpu = 0;
                    for (auto value: vec) {
                        cpu++;
                        for (auto i : value) {
                            pm::MetricFamily mtf;
                            std::string s;
                            google::protobuf::io::StringOutputStream os(&s);
                            mtf.set_name(collectd_name(i.first, cpu));
                            mtf.set_help(ctx.metric_help);
                            fill_metric(mtf, i.second);
                            if (mtf.metric_size() > 0) {
                                std::stringstream ss;
                                if (!write_delimited_to(mtf, &os)) {
                                    seastar_logger.warn("Failed to write protobuf metrics");
                                }
                                rep->_content += s;
                            }
                        }
                    }
                    return make_ready_future<std::unique_ptr<reply>>(std::move(rep));
                });
            });
        };
        r.put(GET, "/metrics", new httpd::function_handler(f, "proto"));
    });
}

}
<|endoftext|>


<commit_before>#ifndef JEZUK_EVENTS_MUTATIONEVENT_H
#define JEZUK_EVENTS_MUTATIONEVENT_H

#include <DOM/Events/Event.hpp>

namespace Arabica
{
namespace DOM
{

namespace Events
{

template<class stringT, class string_adaptorT> class MutationEvent_impl;

template<class stringT, class string_adaptorT = Arabica::default_string_adaptor<stringT> >
class MutationEvent : public Event<stringT, string_adaptorT>
{
  public:
    typedef MutationEvent_impl<stringT, string_adaptorT> MutationEvent_implT;
    typedef Event<stringT, string_adaptorT> EventT;
    typedef DOM::Proxy<MutationEvent_implT> proxy_t;

    MutationEvent() : Event<stringT, string_adaptorT>() { }
    MutationEvent(MutationEvent_impl<stringT, string_adaptorT>* const impl) : Event<stringT, string_adaptorT>(impl) { }
    MutationEvent(const MutationEvent& rhs) : Event<stringT, string_adaptorT>(rhs) { }
    explicit MutationEvent(const Event<stringT, string_adaptorT>& rhs) : Event<stringT, string_adaptorT>(rhs)
    {
      if(dynamic_cast<MutationEvent_impl<stringT, string_adaptorT>*>(rhs.Event<stringT, string_adaptorT>::proxy_t::operator*()) == 0)
        throw DOMBadCast("Element");
    } // Element
    virtual ~MutationEvent() { }
    bool operator==(const MutationEvent& rhs) const { return proxy_t::operator==(rhs); }
    bool operator!=(const MutationEvent& rhs) const { return proxy_t::operator!=(rhs); }
    bool operator==(int dummy) const { return proxy_t::operator==(dummy); }
    bool operator!=(int dummy) const { return proxy_t::operator!=(dummy); }

    MutationEvent& operator=(const MutationEvent& rhs)
    {
      proxy_t::operator=(rhs);
      return *this;
    } // operator=

    /////////////////////////////////////////////
    // MutationEvent methods
    enum AttrChange
    {
      MODIFICATION = 1,
      ADDITION = 2,
      REMOVAL = 3
    }; // enum Change

    DOM::Node<stringT> getRelatedNode() const { return mImpl()->getRelatedNode(); }

    stringT getPrevValue() const { return mImpl()->getPrevValue(); }

    stringT getNextValue() const { return mImpl()->getNextValue(); }

    stringT getAttrName() const { return mImpl()->getAttrName(); }

    AttrChange getAttrChange() const { return mImpl()->getAttrChange(); }

    void initMutationEvent(const stringT& typeArg,
                           bool canBubble,
                           bool canCancel,
                           DOM::Node<stringT> relatedNode,
                           const stringT& prevValueArg,
                           const stringT& nextValueArg,
                           const stringT& attrNameArg,
                           AttrChange attrChangeArg)
    {
      mImpl()->initMutationEvent(typeArg, canBubble, canCancel, relatedNode,
                                 prevValueArg, nextValueArg, attrNameArg, attrChangeArg);
    } // initMutationEvent

  private:
  MutationEvent_implT* mImpl() const { return dynamic_cast<MutationEvent_implT*>(EventT::proxy_t::operator*()); }
}; // class Event

///////////////////////////////////////////////////////////
// Event_impl
template<class stringT, class string_adaptorT = Arabica::default_string_adaptor<stringT> >
class MutationEvent_impl : virtual public Event_impl<stringT, string_adaptorT>
{
  public:
    ///////////////////////////////////
    // MutationEvent methods
    virtual DOM::Node<stringT> getRelatedNode() const = 0;

    virtual stringT getPrevValue() const = 0;

    virtual stringT getNextValue() const = 0;

    virtual stringT getAttrName() const = 0;

    virtual typename MutationEvent<stringT, string_adaptorT>::AttrChange getAttrChange() const = 0;

    virtual void initMutationEvent(const stringT& typeArg,
                                   bool canBubble,
                                   bool canCancel,
                                   DOM::Node<stringT> relatedNode,
                                   const stringT& prevValueArg,
                                   const stringT& nextValueArg,
                                   const stringT& attrNameArg,
                                   typename MutationEvent<stringT, string_adaptorT>::AttrChange attrChangeArg) = 0;

}; // class Event_impl

} // namespace Events

} // namespace DOM
} // namespace Arabica

#endif
// end of file
<commit_msg>Accept const char* to initMutationEvent<commit_after>#ifndef JEZUK_EVENTS_MUTATIONEVENT_H
#define JEZUK_EVENTS_MUTATIONEVENT_H

#include <DOM/Events/Event.hpp>

namespace Arabica
{
namespace DOM
{

namespace Events
{

template<class stringT, class string_adaptorT> class MutationEvent_impl;

template<class stringT, class string_adaptorT = Arabica::default_string_adaptor<stringT> >
class MutationEvent : public Event<stringT, string_adaptorT>
{
  public:
    typedef MutationEvent_impl<stringT, string_adaptorT> MutationEvent_implT;
    typedef Event<stringT, string_adaptorT> EventT;
    typedef DOM::Proxy<MutationEvent_implT> proxy_t;

    MutationEvent() : Event<stringT, string_adaptorT>() { }
    MutationEvent(MutationEvent_impl<stringT, string_adaptorT>* const impl) : Event<stringT, string_adaptorT>(impl) { }
    MutationEvent(const MutationEvent& rhs) : Event<stringT, string_adaptorT>(rhs) { }
    explicit MutationEvent(const Event<stringT, string_adaptorT>& rhs) : Event<stringT, string_adaptorT>(rhs)
    {
      if(dynamic_cast<MutationEvent_impl<stringT, string_adaptorT>*>(rhs.Event<stringT, string_adaptorT>::proxy_t::operator*()) == 0)
        throw DOMBadCast("Element");
    } // Element
    virtual ~MutationEvent() { }
    bool operator==(const MutationEvent& rhs) const { return proxy_t::operator==(rhs); }
    bool operator!=(const MutationEvent& rhs) const { return proxy_t::operator!=(rhs); }
    bool operator==(int dummy) const { return proxy_t::operator==(dummy); }
    bool operator!=(int dummy) const { return proxy_t::operator!=(dummy); }

    MutationEvent& operator=(const MutationEvent& rhs)
    {
      proxy_t::operator=(rhs);
      return *this;
    } // operator=

    /////////////////////////////////////////////
    // MutationEvent methods
    enum AttrChange
    {
      MODIFICATION = 1,
      ADDITION = 2,
      REMOVAL = 3
    }; // enum Change

    DOM::Node<stringT> getRelatedNode() const { return mImpl()->getRelatedNode(); }

    stringT getPrevValue() const { return mImpl()->getPrevValue(); }

    stringT getNextValue() const { return mImpl()->getNextValue(); }

    stringT getAttrName() const { return mImpl()->getAttrName(); }

    AttrChange getAttrChange() const { return mImpl()->getAttrChange(); }

    void initMutationEvent(const char* typeArg,
                           bool canBubble,
                           bool canCancel,
                           DOM::Node<stringT> relatedNode,
                           const stringT& prevValueArg,
                           const stringT& nextValueArg,
                           const stringT& attrNameArg,
                           AttrChange attrChangeArg)
    {
      mImpl()->initMutationEvent(string_adaptorT::convert_from_utf8(typeArg),
                                 canBubble, canCancel, relatedNode,
                                 prevValueArg, nextValueArg, attrNameArg, attrChangeArg);
    } // initMutationEvent

  private:
  MutationEvent_implT* mImpl() const { return dynamic_cast<MutationEvent_implT*>(EventT::proxy_t::operator*()); }
}; // class Event

///////////////////////////////////////////////////////////
// Event_impl
template<class stringT, class string_adaptorT = Arabica::default_string_adaptor<stringT> >
class MutationEvent_impl : virtual public Event_impl<stringT, string_adaptorT>
{
  public:
    ///////////////////////////////////
    // MutationEvent methods
    virtual DOM::Node<stringT> getRelatedNode() const = 0;

    virtual stringT getPrevValue() const = 0;

    virtual stringT getNextValue() const = 0;

    virtual stringT getAttrName() const = 0;

    virtual typename MutationEvent<stringT, string_adaptorT>::AttrChange getAttrChange() const = 0;

    virtual void initMutationEvent(const stringT& typeArg,
                                   bool canBubble,
                                   bool canCancel,
                                   DOM::Node<stringT> relatedNode,
                                   const stringT& prevValueArg,
                                   const stringT& nextValueArg,
                                   const stringT& attrNameArg,
                                   typename MutationEvent<stringT, string_adaptorT>::AttrChange attrChangeArg) = 0;

}; // class Event_impl

} // namespace Events

} // namespace DOM
} // namespace Arabica

#endif
// end of file
<|endoftext|>


<commit_before>/*
 * This File is part of Davix, The IO library for HTTP based protocols
 * Copyright (C) 2013  Adrien Devresse <adrien.devresse@cern.ch>, CERN
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
*/
#ifndef DAVIX_CONFIG
#define DAVIX_CONFIG

#include <functional>

#ifndef __DAVIX_INSIDE__
#error "Only davix.hpp should be included."
#endif

//
// export
//
#ifndef DAVIX_EXPORT
#define DAVIX_EXPORT __attribute__((visibility("default")))
#endif

//
// detect GCC
//
#if (defined(__GNUC__) || defined(__GNUG__)) && !(defined(__clang__) || defined(__INTEL_COMPILER))
#   ifndef __DAVIX_COMPILER_GCC
#       define __DAVIX_COMPILER_GCC
#   endif
#endif

//
// detect CXX11 support
//
#if ( (__cplusplus > 199711L) \
     || (defined (DAVIX_FORCE_CXX11)) \
     || (defined __GXX_EXPERIMENTAL_CXX0X__) )
#   ifndef __DAVIX_CX11_SUPPORT
#       define __DAVIX_CX11_SUPPORT
#   endif
#endif

//
// detect TR1 support
//
#if ( (defined DAVIX_FORCE_TR1) \
      || (defined __DAVIX_COMPILER_GCC) \
      || (defined HAVE_TR1_SUPPORT))
#   ifndef __DAVIX_TR1_SUPPORT
#       define __DAVIX_TR1_SUPPORT
#endif

#endif

//
// include tr1 namespace
//

#if (!(defined __DAVIX_CX11_SUPPORT) \
    && (defined __DAVIX_TR1_SUPPORT))
#       include <tr1/functional>

namespace std{
    using namespace std::tr1;
}

#endif

//
// enable STD_FUNCTION_DECL
//
#if ((defined __DAVIX_CX11_SUPPORT) \
    || (defined __DAVIX_TR1_SUPPORT) \
    || (defined HAVE_STD_FUNCTION))
#   ifndef __DAVIX_HAS_STD_FUNCTION
#       define __DAVIX_HAS_STD_FUNCTION
#   endif
#endif

//
// davix preproc facilities
//
#undef DAVIX_C_DECL_BEGIN
#undef DAVIX_C_DECL_END
#ifdef __cplusplus
#define DAVIX_C_DECL_BEGIN \
        extern "C" {
#define DAVIX_C_DECL_END }
#else
#define DAVIX_C_DECL_BEGIN  // void
#define DAVIX_C_DECL_END    // void
#endif

//
// compat 32 bits
#if  (( __WORDSIZE == 32 ) \
        || ( SIZE_MAX ==  (4294967295U) )) \
     && !(defined __DAVIX_COMPAT_32) \
     && !(defined __NO_DAVIX_COMPAT_32)
#define __DAVIX_COMPAT_32
#endif

#endif // DAVIX_TYPES_HPP
<commit_msg> add TR1 memory for EL5 compilation<commit_after>/*
 * This File is part of Davix, The IO library for HTTP based protocols
 * Copyright (C) 2013  Adrien Devresse <adrien.devresse@cern.ch>, CERN
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
*/
#ifndef DAVIX_CONFIG
#define DAVIX_CONFIG

#include <functional>

#ifndef __DAVIX_INSIDE__
#error "Only davix.hpp should be included."
#endif

//
// export
//
#ifndef DAVIX_EXPORT
#define DAVIX_EXPORT __attribute__((visibility("default")))
#endif

//
// detect GCC
//
#if (defined(__GNUC__) || defined(__GNUG__)) && !(defined(__clang__) || defined(__INTEL_COMPILER))
#   ifndef __DAVIX_COMPILER_GCC
#       define __DAVIX_COMPILER_GCC
#   endif
#endif

//
// detect CXX11 support
//
#if ( (__cplusplus > 199711L) \
     || (defined (DAVIX_FORCE_CXX11)) \
     || (defined __GXX_EXPERIMENTAL_CXX0X__) )
#   ifndef __DAVIX_CX11_SUPPORT
#       define __DAVIX_CX11_SUPPORT
#   endif
#endif

//
// detect TR1 support
//
#if ( (defined DAVIX_FORCE_TR1) \
      || (defined __DAVIX_COMPILER_GCC) \
      || (defined HAVE_TR1_SUPPORT))
#   ifndef __DAVIX_TR1_SUPPORT
#       define __DAVIX_TR1_SUPPORT
#endif

#endif

//
// include tr1 namespace
//

#if (!(defined __DAVIX_CX11_SUPPORT) \
    && (defined __DAVIX_TR1_SUPPORT))
#       include <tr1/functional>
#       include <tr1/memory>

namespace std{
    using namespace std::tr1;
}

#endif

//
// enable STD_FUNCTION_DECL
//
#if ((defined __DAVIX_CX11_SUPPORT) \
    || (defined __DAVIX_TR1_SUPPORT) \
    || (defined HAVE_STD_FUNCTION))
#   ifndef __DAVIX_HAS_STD_FUNCTION
#       define __DAVIX_HAS_STD_FUNCTION
#   endif
#endif

//
// davix preproc facilities
//
#undef DAVIX_C_DECL_BEGIN
#undef DAVIX_C_DECL_END
#ifdef __cplusplus
#define DAVIX_C_DECL_BEGIN \
        extern "C" {
#define DAVIX_C_DECL_END }
#else
#define DAVIX_C_DECL_BEGIN  // void
#define DAVIX_C_DECL_END    // void
#endif

//
// compat 32 bits
#if  (( __WORDSIZE == 32 ) \
        || ( SIZE_MAX ==  (4294967295U) )) \
     && !(defined __DAVIX_COMPAT_32) \
     && !(defined __NO_DAVIX_COMPAT_32)
#define __DAVIX_COMPAT_32
#endif

#endif // DAVIX_TYPES_HPP
<|endoftext|>


<commit_before>/**
 * \file
 * \brief SignalsCatcher class header
 *
 * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2015-04-16
 */

#ifndef INCLUDE_DISTORTOS_SIGNALSCATCHER_HPP_
#define INCLUDE_DISTORTOS_SIGNALSCATCHER_HPP_

#include "distortos/synchronization/SignalsCatcherControlBlock.hpp"

namespace distortos
{

namespace synchronization
{

class SignalsReceiverControlBlock;

}	// namespace synchronization

/// SignalsCatcher class is a container for synchronization::SignalsCatcherControlBlock
class SignalsCatcher
{
	friend class synchronization::SignalsReceiverControlBlock;

public:

	/// import Storage type alias from synchronization::SignalsCatcherControlBlock
	using Storage = synchronization::SignalsCatcherControlBlock::Storage;

	/**
	 * \brief SignalsCatcher's constructor
	 *
	 * \param [in] storageBegin is a pointer to first element of storage for
	 * synchronization::SignalsCatcherControlBlock::Association objects
	 * \param [in] storageEnd is a pointer to "one past the last" element of storage for
	 * synchronization::SignalsCatcherControlBlock::Association objects
	 */

	constexpr SignalsCatcher(Storage* const storageBegin, Storage* const storageEnd) :
			signalsCatcherControlBlock_{storageBegin, storageEnd}
	{

	}

private:

	/// contained synchronization::SignalsCatcherControlBlock object
	synchronization::SignalsCatcherControlBlock signalsCatcherControlBlock_;
};

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_SIGNALSCATCHER_HPP_
<commit_msg>SignalsCatcher: add helper constructor with array as argument and size of array deduced by template<commit_after>/**
 * \file
 * \brief SignalsCatcher class header
 *
 * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2015-04-16
 */

#ifndef INCLUDE_DISTORTOS_SIGNALSCATCHER_HPP_
#define INCLUDE_DISTORTOS_SIGNALSCATCHER_HPP_

#include "distortos/synchronization/SignalsCatcherControlBlock.hpp"

namespace distortos
{

namespace synchronization
{

class SignalsReceiverControlBlock;

}	// namespace synchronization

/// SignalsCatcher class is a container for synchronization::SignalsCatcherControlBlock
class SignalsCatcher
{
	friend class synchronization::SignalsReceiverControlBlock;

public:

	/// import Storage type alias from synchronization::SignalsCatcherControlBlock
	using Storage = synchronization::SignalsCatcherControlBlock::Storage;

	/**
	 * \brief SignalsCatcher's constructor
	 *
	 * \param [in] storageBegin is a pointer to first element of storage for
	 * synchronization::SignalsCatcherControlBlock::Association objects
	 * \param [in] storageEnd is a pointer to "one past the last" element of storage for
	 * synchronization::SignalsCatcherControlBlock::Association objects
	 */

	constexpr SignalsCatcher(Storage* const storageBegin, Storage* const storageEnd) :
			signalsCatcherControlBlock_{storageBegin, storageEnd}
	{

	}

	/**
	 * \brief SignalsCatcher's constructor
	 *
	 * \param N is the number of elements in \a storage array
	 *
	 * \param [in] storage is a reference to array of Storage elements
	 */

	template<size_t N>
	constexpr explicit SignalsCatcher(Storage (& storage)[N]) :
			SignalsCatcher{std::begin(storage), std::end(storage)}
	{

	}

private:

	/// contained synchronization::SignalsCatcherControlBlock object
	synchronization::SignalsCatcherControlBlock signalsCatcherControlBlock_;
};

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_SIGNALSCATCHER_HPP_
<|endoftext|>


<commit_before>/******************************************************************************
* Copyright (c) 2012, Howard Butler, hobu.inc@gmail.com
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in
*       the documentation and/or other materials provided
*       with the distribution.
*     * Neither the name of Hobu, Inc. or Flaxen Geo Consulting 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/

#ifndef INCLUDED_PDAL_DRIVER_SOCI_READER_HPP
#define INCLUDED_PDAL_DRIVER_SOCI_READER_HPP

#include <pdal/Reader.hpp>
#include <pdal/ReaderIterator.hpp>
#include <pdal/GDALUtils.hpp>

#include <pdal/drivers/soci/common.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/scoped_array.hpp>

#include <vector>

namespace pdal
{
namespace drivers
{
namespace soci
{

class PDAL_DLL Reader : public pdal::Reader
{
public:
    SET_STAGE_NAME("drivers.soci.reader", "SOCI Reader")

    Reader(const Options&);
    ~Reader();

    virtual void initialize();
    virtual const Options getDefaultOptions() const;
    virtual void addDefaultDimensions();

    bool supportsIterator(StageIteratorType t) const
    {
        if (t == StageIterator_Sequential) return true;
        return false;
    }

    virtual boost::uint64_t getNumPoints() const;

    pdal::StageSequentialIterator* createSequentialIterator(PointBuffer& buffer) const;

    QueryType getQueryType() const
    {
        return m_query_type;
    }
    QueryType describeQueryType(std::string const& query) const;

    inline DatabaseType getDatabaseType() const { return m_database_type; }
    pdal::Schema fetchSchema(std::string const& query) const;
    pdal::SpatialReference fetchSpatialReference(std::string const& query) const;

private:

    Reader& operator=(const Reader&); // not implemented
    Reader(const Reader&); // not implemented
    //

    DatabaseType m_database_type;
    QueryType m_query_type;

    // Connection m_connection;
    // Statement m_initialQueryStatement;
    // QueryType m_querytype;
    //
    // BlockPtr m_block;
    // boost::uint32_t m_capacity;
    //
    // // Fields in the form of NAME:TYPE
    // std::map<std::string, int> m_fields;
    //
    // boost::shared_ptr<pdal::gdal::Debug> m_gdal_debug;
    mutable boost::uint64_t m_cachedPointCount;

    #ifdef PDAL_HAVE_SOCI
        ::soci::session* m_session;
    #else
        void* m_session;
    #endif

};

namespace iterators
{

namespace sequential
{

    typedef boost::shared_ptr<PointBuffer> BufferPtr;
    typedef std::map<int, BufferPtr> BufferMap;

class IteratorBase
{
public:
    IteratorBase(const pdal::drivers::soci::Reader& reader);
    ~IteratorBase();

protected:
    const pdal::drivers::soci::Reader& getReader() const;

    boost::uint32_t myReadBuffer(PointBuffer& data);
    // boost::uint32_t unpackOracleData(PointBuffer& data);
    //
    boost::uint32_t myReadClouds(PointBuffer& data);
    boost::uint32_t myReadBlocks(PointBuffer& data, ::soci::statement& statement, ::soci::row& row);
    //
    BufferPtr fetchPointBuffer( boost::int32_t const& cloud_id,
                                std::string const& schema_xml);

    bool m_at_end;

    DatabaseType m_database_type;
    QueryType m_query_type;

    boost::int32_t m_active_cloud_id;
    BufferPtr m_active_buffer;
    BufferMap m_buffers;
    boost::uint32_t m_buffer_position;

private:
    const pdal::drivers::soci::Reader& m_reader;

    #ifdef PDAL_HAVE_SOCI
        ::soci::session* m_session;
    #else
        void* m_session;
    #endif

    ::soci::statement getNextCloud(   std::string const& cloud_table_name,
                                      boost::int32_t& cloud_id,
                                      ::soci::row& r);
    void readBlob(::soci::row& block,
                  boost::uint32_t howMany);
    void fillUserBuffer(PointBuffer& user_buffer);
    //
    void copyDatabaseData(PointBuffer& source,
                          PointBuffer& destination,
                          Dimension const& dest_dim,
                          boost::uint32_t source_starting_position,
                          boost::uint32_t destination_starting_position,
                          boost::uint32_t howMany);
    // pdal::Bounds<double> getBounds(Statement statement, BlockPtr block);
    IteratorBase& operator=(const IteratorBase&); // not implemented
    IteratorBase(const IteratorBase&); // not implemented;

};

class Reader : public IteratorBase, public pdal::StageSequentialIterator
{
public:
    Reader(const pdal::drivers::soci::Reader& reader, PointBuffer& buffer);
    ~Reader();

private:
    boost::uint64_t skipImpl(boost::uint64_t count);
    boost::uint32_t readBufferImpl(PointBuffer& data);
    bool atEndImpl() const;
};

} // sequential

} // iterators
}
}
} // namespace pdal::driver::oci

#endif // INCLUDED_PDAL_DRIVER_OCI_READER_HPP
<commit_msg>don't include GDAL stuff in soci driver<commit_after>/******************************************************************************
* Copyright (c) 2012, Howard Butler, hobu.inc@gmail.com
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in
*       the documentation and/or other materials provided
*       with the distribution.
*     * Neither the name of Hobu, Inc. or Flaxen Geo Consulting 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/

#ifndef INCLUDED_PDAL_DRIVER_SOCI_READER_HPP
#define INCLUDED_PDAL_DRIVER_SOCI_READER_HPP

#include <pdal/Reader.hpp>
#include <pdal/ReaderIterator.hpp>

#include <pdal/drivers/soci/common.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/scoped_array.hpp>

#include <vector>

namespace pdal
{
namespace drivers
{
namespace soci
{

class PDAL_DLL Reader : public pdal::Reader
{
public:
    SET_STAGE_NAME("drivers.soci.reader", "SOCI Reader")

    Reader(const Options&);
    ~Reader();

    virtual void initialize();
    virtual const Options getDefaultOptions() const;
    virtual void addDefaultDimensions();

    bool supportsIterator(StageIteratorType t) const
    {
        if (t == StageIterator_Sequential) return true;
        return false;
    }

    virtual boost::uint64_t getNumPoints() const;

    pdal::StageSequentialIterator* createSequentialIterator(PointBuffer& buffer) const;

    QueryType getQueryType() const
    {
        return m_query_type;
    }
    QueryType describeQueryType(std::string const& query) const;

    inline DatabaseType getDatabaseType() const { return m_database_type; }
    pdal::Schema fetchSchema(std::string const& query) const;
    pdal::SpatialReference fetchSpatialReference(std::string const& query) const;

private:

    Reader& operator=(const Reader&); // not implemented
    Reader(const Reader&); // not implemented
    //

    DatabaseType m_database_type;
    QueryType m_query_type;

    // Connection m_connection;
    // Statement m_initialQueryStatement;
    // QueryType m_querytype;
    //
    // BlockPtr m_block;
    // boost::uint32_t m_capacity;
    //
    // // Fields in the form of NAME:TYPE
    // std::map<std::string, int> m_fields;
    //
    // boost::shared_ptr<pdal::gdal::Debug> m_gdal_debug;
    mutable boost::uint64_t m_cachedPointCount;

    #ifdef PDAL_HAVE_SOCI
        ::soci::session* m_session;
    #else
        void* m_session;
    #endif

};

namespace iterators
{

namespace sequential
{

    typedef boost::shared_ptr<PointBuffer> BufferPtr;
    typedef std::map<int, BufferPtr> BufferMap;

class IteratorBase
{
public:
    IteratorBase(const pdal::drivers::soci::Reader& reader);
    ~IteratorBase();

protected:
    const pdal::drivers::soci::Reader& getReader() const;

    boost::uint32_t myReadBuffer(PointBuffer& data);
    // boost::uint32_t unpackOracleData(PointBuffer& data);
    //
    boost::uint32_t myReadClouds(PointBuffer& data);
    boost::uint32_t myReadBlocks(PointBuffer& data, ::soci::statement& statement, ::soci::row& row);
    //
    BufferPtr fetchPointBuffer( boost::int32_t const& cloud_id,
                                std::string const& schema_xml);

    bool m_at_end;

    DatabaseType m_database_type;
    QueryType m_query_type;

    boost::int32_t m_active_cloud_id;
    BufferPtr m_active_buffer;
    BufferMap m_buffers;
    boost::uint32_t m_buffer_position;

private:
    const pdal::drivers::soci::Reader& m_reader;

    #ifdef PDAL_HAVE_SOCI
        ::soci::session* m_session;
    #else
        void* m_session;
    #endif

    ::soci::statement getNextCloud(   std::string const& cloud_table_name,
                                      boost::int32_t& cloud_id,
                                      ::soci::row& r);
    void readBlob(::soci::row& block,
                  boost::uint32_t howMany);
    void fillUserBuffer(PointBuffer& user_buffer);
    //
    void copyDatabaseData(PointBuffer& source,
                          PointBuffer& destination,
                          Dimension const& dest_dim,
                          boost::uint32_t source_starting_position,
                          boost::uint32_t destination_starting_position,
                          boost::uint32_t howMany);
    // pdal::Bounds<double> getBounds(Statement statement, BlockPtr block);
    IteratorBase& operator=(const IteratorBase&); // not implemented
    IteratorBase(const IteratorBase&); // not implemented;

};

class Reader : public IteratorBase, public pdal::StageSequentialIterator
{
public:
    Reader(const pdal::drivers::soci::Reader& reader, PointBuffer& buffer);
    ~Reader();

private:
    boost::uint64_t skipImpl(boost::uint64_t count);
    boost::uint32_t readBufferImpl(PointBuffer& data);
    bool atEndImpl() const;
};

} // sequential

} // iterators
}
}
} // namespace pdal::driver::oci

#endif // INCLUDED_PDAL_DRIVER_OCI_READER_HPP
<|endoftext|>


<commit_before>#include "parser/xmlParser.hpp"

// Too many false-positives involving default parameters in library functions
#pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"

XMLParser::XMLParser() {}

XMLParser& XMLParser::parse(char* str) {
  rapidxml::xml_document<char> doc;
  try {
    doc.parse<0>(str);
  } catch (rapidxml::parse_error& pe) {
    throw XMLParseError("XML parsing failed", {
      METADATA_PAIRS,
      {"xml error", pe.what()},
      {"position", std::to_string(*pe.where<int>())}
    });
  }
  auto rootNode = Node<BlockNode>::dynPtrCast(parseXMLNode(doc.first_node()));
  if (rootNode == nullptr) throw XMLParseError("Root node isn't a block node", {
    METADATA_PAIRS,
    {"tag name", doc.first_node()->name()}
  });
  tree = std::make_unique<AST>(AST(rootNode));
  return *this;
}

XMLParser& XMLParser::parse(rapidxml::file<char> xmlFile) {
  parse(xmlFile.data());
  return *this;
}

void XMLParser::parseChildren(rapidxml::xml_node<>* node, ASTNode::Link target) {
  for (auto child = node->first_node(); child; child = child->next_sibling()) {
    auto parsedChild = parseXMLNode(child);
    target->addChild(parsedChild);
  }
}

static Visibility fromString(std::string str) {
  Visibility vis =
    str == "private" ? PRIVATE :
    str == "protected" ? PROTECTED :
    str == "public" ? PUBLIC :
      INVALID;
  if (vis == INVALID) throw XMLParseError("Invalid visibility for member", {
    METADATA_PAIRS,
    {"invalid value", str}
  });
  return vis;
}

ASTNode::Link XMLParser::parseXMLNode(rapidxml::xml_node<>* node) {
  auto safeAttr = [node](std::string what, std::string defaultValue = "") -> std::string {
    auto attr = node->first_attribute(what.c_str());
    if (attr != nullptr) return attr->value();
    else return defaultValue;
  };
  auto requiredAttr = [node](std::string what) -> std::string {
    auto attr = node->first_attribute(what.c_str());
    if (attr != nullptr) return attr->value();
    else throw XMLParseError("Can't find required attribute", {
      METADATA_PAIRS,
      {"missing attribute", what}
    });
  };
  auto funArgs = [node, &safeAttr]() -> FunctionSignature::Arguments {
    FunctionSignature::Arguments args {};
    std::vector<std::string> stringArgs = split(safeAttr("args"), ',');
    for (auto& arg : stringArgs) {
      std::vector<std::string> namePlusTypes = split(arg, ':');
      std::vector<std::string> types = split(namePlusTypes[1], ' ');
      args.push_back(std::make_pair(namePlusTypes[0], TypeList(ALL(types))));
    }
    return args;
  };
  auto funRet = [node, &safeAttr]() -> TypeInfo {
    std::vector<std::string> returnTypes = split(safeAttr("return"), ' ');
    return returnTypes.size() == 0 ? nullptr : TypeInfo(TypeList(ALL(returnTypes)));
  };
  auto funBlock = [=](Node<FunctionNode>::Link f) {
    if (!f->isForeign()) {
      auto codeBlock = node->first_node("block");
      if (codeBlock == nullptr) throw XMLParseError("Method missing code block", {METADATA_PAIRS});
      f->setCode(Node<BlockNode>::staticPtrCast(parseXMLNode(codeBlock)));
    }
  };
  auto getVisibility = [node, &safeAttr]() -> Visibility {
    return fromString(safeAttr("visibility", "private"));
  };
  auto boolAttr = [node, &safeAttr](std::string what) -> bool {
    return safeAttr(what, "false") == "true";
  };

  if (node == nullptr) throw XMLParseError("Null node", {METADATA_PAIRS});
  std::string name = node->name();
  if (name == "block") {
    std::string type = safeAttr("type", "code");
    BlockType bt =
      type == "root" ? ROOT_BLOCK :
      type == "if" ? IF_BLOCK :
      type == "function" ? FUNCTION_BLOCK : CODE_BLOCK;
    auto block = Node<BlockNode>::make(bt);
    parseChildren(node, block);
    return block;
  } else if (name == "return") {
    auto retNode = Node<ReturnNode>::make();
    auto val = node->first_node("expr");
    if (val != nullptr) retNode->setValue(Node<ExpressionNode>::dynPtrCast(parseXMLNode(val)));
    return retNode;
  } else if (name == "expr") {
    TokenType tokenType = TT::findByPrettyName(requiredAttr("type"));
    std::string data = requiredAttr("value");
    std::unique_ptr<Token> content;
    if (tokenType == TT::OPERATOR) {
      content = std::make_unique<Token>(tokenType, Operator::find(data), defaultTrace);
    } else {
      content = std::make_unique<Token>(tokenType, data, defaultTrace);
    }
    auto expr = Node<ExpressionNode>::make(*content);
    parseChildren(node, expr);
    return expr;
  } else if (name == "decl") {
    Node<DeclarationNode>::Link decl;
    std::string ident = requiredAttr("ident");
    bool isDynamic = boolAttr("dynamic");
    if (isDynamic) {
      decl = Node<DeclarationNode>::make(ident, TypeList {});
    } else {
      std::string tlValue = requiredAttr("types");
      auto vec = split(tlValue, ' ');
      decl = Node<DeclarationNode>::make(ident, TypeList(ALL(vec)));
    }
    auto expr = node->first_node("expr");
    if (expr != nullptr) {
      decl->setInit(Node<ExpressionNode>::dynPtrCast(parseXMLNode(expr)));
    }
    return decl;
  } else if (name == "branch") {
    auto branch = Node<BranchNode>::make();
    auto cond = node->first_node();
    if (cond == nullptr) throw XMLParseError("Missing condition in branch", {METADATA_PAIRS});
    branch->setCondition(Node<ExpressionNode>::dynPtrCast(parseXMLNode(cond)));
    auto success = cond->next_sibling();
    if (success == nullptr) throw XMLParseError("Missing success node in branch", {METADATA_PAIRS});
    branch->setSuccessBlock(Node<BlockNode>::dynPtrCast(parseXMLNode(success)));
    auto blockFailiure = success->next_sibling("block");
    if (blockFailiure != nullptr) {
      branch->setFailiureBlock(Node<BlockNode>::dynPtrCast(parseXMLNode(blockFailiure)));
    }
    auto branchFailiure = success->next_sibling("branch");
    if (branchFailiure != nullptr) {
      branch->setFailiureBlock(Node<BranchNode>::dynPtrCast(parseXMLNode(branchFailiure)));
    }
    return branch;
  } else if (name == "loop") {
    auto loop = Node<LoopNode>::make();
    auto init = node->first_node("loop_init");
    if (init != nullptr) {
      loop->setInit(Node<DeclarationNode>::dynPtrCast(parseXMLNode(init)));
    }
    auto cond = node->first_node("loop_condition");
    if (cond != nullptr) {
      loop->setCondition(Node<ExpressionNode>::dynPtrCast(parseXMLNode(cond)));
    }
    auto update = node->first_node("loop_update");
    if (update != nullptr) {
      loop->setUpdate(Node<ExpressionNode>::dynPtrCast(parseXMLNode(update)));
    }
    auto code = node->first_node("block");
    if (code != nullptr) {
      loop->setCode(Node<BlockNode>::dynPtrCast(parseXMLNode(code)));
    }
    return loop;
  } else if (name == "loop_init" || name == "loop_condition" || name == "loop_update") {
    return parseXMLNode(node->first_node());
  } else if (name == "break") {
    return Node<BreakLoopNode>::make();
  } else if (name == "function") {
    std::string ident = safeAttr("ident");
    bool isForeign = boolAttr("foreign");
    auto n = Node<FunctionNode>::make(ident, FunctionSignature(funRet(), funArgs()), isForeign);
    funBlock(n);
    if (isForeign && ident.empty()) throw XMLParseError("Can't have anonymous foreign function", {METADATA_PAIRS});
    return n;
  } else if (name == "type") {
    std::string typeName = requiredAttr("name");
    std::vector<std::string> inheritTypes = split(safeAttr("inherits"), ' ');
    auto typeNode = Node<TypeNode>::make(typeName, TypeList(ALL(inheritTypes)));
    parseChildren(node, typeNode);
    return typeNode;
  } else if (name == "member") {
    std::string ident = requiredAttr("ident");
    std::vector<std::string> types = split(safeAttr("types"), ' ');
    auto member = Node<MemberNode>::make(ident, TypeList(ALL(types)), boolAttr("static"), getVisibility());
    auto init = node->first_node("expr");
    if (init != nullptr) {
      member->setInit(Node<ExpressionNode>::staticPtrCast(parseXMLNode(init)));
    }
    return member;
  } else if (name == "method") {
    std::string ident = safeAttr("ident");
    bool isForeign = boolAttr("foreign");
    auto method = Node<MethodNode>::make(ident, FunctionSignature(funRet(), funArgs()), getVisibility(), boolAttr("static"), isForeign);
    funBlock(method);
    if (isForeign && ident.empty()) throw XMLParseError("Can't have anonymous foreign method", {METADATA_PAIRS});
    return method;
  } else if (name == "constructor") {
    auto constructor = Node<ConstructorNode>::make(funArgs(), getVisibility());
    funBlock(constructor);
    return constructor;
  }
  throw XMLParseError("Unknown type of node", {METADATA_PAIRS, {"node name", name}});
}

XMLParseError::XMLParseError(std::string msg, ErrorData data):
  InternalError("XMLParseError", msg, data) {}
<commit_msg>Fix unknown pragma warning in clang<commit_after>#include "parser/xmlParser.hpp"

#ifndef __clang__
#ifdef __GNUG__
// Too many false-positives involving default parameters in library functions
#pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
#endif
#endif

XMLParser::XMLParser() {}

XMLParser& XMLParser::parse(char* str) {
  rapidxml::xml_document<char> doc;
  try {
    doc.parse<0>(str);
  } catch (rapidxml::parse_error& pe) {
    throw XMLParseError("XML parsing failed", {
      METADATA_PAIRS,
      {"xml error", pe.what()},
      {"position", std::to_string(*pe.where<int>())}
    });
  }
  auto rootNode = Node<BlockNode>::dynPtrCast(parseXMLNode(doc.first_node()));
  if (rootNode == nullptr) throw XMLParseError("Root node isn't a block node", {
    METADATA_PAIRS,
    {"tag name", doc.first_node()->name()}
  });
  tree = std::make_unique<AST>(AST(rootNode));
  return *this;
}

XMLParser& XMLParser::parse(rapidxml::file<char> xmlFile) {
  parse(xmlFile.data());
  return *this;
}

void XMLParser::parseChildren(rapidxml::xml_node<>* node, ASTNode::Link target) {
  for (auto child = node->first_node(); child; child = child->next_sibling()) {
    auto parsedChild = parseXMLNode(child);
    target->addChild(parsedChild);
  }
}

static Visibility fromString(std::string str) {
  Visibility vis =
    str == "private" ? PRIVATE :
    str == "protected" ? PROTECTED :
    str == "public" ? PUBLIC :
      INVALID;
  if (vis == INVALID) throw XMLParseError("Invalid visibility for member", {
    METADATA_PAIRS,
    {"invalid value", str}
  });
  return vis;
}

ASTNode::Link XMLParser::parseXMLNode(rapidxml::xml_node<>* node) {
  auto safeAttr = [node](std::string what, std::string defaultValue = "") -> std::string {
    auto attr = node->first_attribute(what.c_str());
    if (attr != nullptr) return attr->value();
    else return defaultValue;
  };
  auto requiredAttr = [node](std::string what) -> std::string {
    auto attr = node->first_attribute(what.c_str());
    if (attr != nullptr) return attr->value();
    else throw XMLParseError("Can't find required attribute", {
      METADATA_PAIRS,
      {"missing attribute", what}
    });
  };
  auto funArgs = [node, &safeAttr]() -> FunctionSignature::Arguments {
    FunctionSignature::Arguments args {};
    std::vector<std::string> stringArgs = split(safeAttr("args"), ',');
    for (auto& arg : stringArgs) {
      std::vector<std::string> namePlusTypes = split(arg, ':');
      std::vector<std::string> types = split(namePlusTypes[1], ' ');
      args.push_back(std::make_pair(namePlusTypes[0], TypeList(ALL(types))));
    }
    return args;
  };
  auto funRet = [node, &safeAttr]() -> TypeInfo {
    std::vector<std::string> returnTypes = split(safeAttr("return"), ' ');
    return returnTypes.size() == 0 ? nullptr : TypeInfo(TypeList(ALL(returnTypes)));
  };
  auto funBlock = [=](Node<FunctionNode>::Link f) {
    if (!f->isForeign()) {
      auto codeBlock = node->first_node("block");
      if (codeBlock == nullptr) throw XMLParseError("Method missing code block", {METADATA_PAIRS});
      f->setCode(Node<BlockNode>::staticPtrCast(parseXMLNode(codeBlock)));
    }
  };
  auto getVisibility = [node, &safeAttr]() -> Visibility {
    return fromString(safeAttr("visibility", "private"));
  };
  auto boolAttr = [node, &safeAttr](std::string what) -> bool {
    return safeAttr(what, "false") == "true";
  };

  if (node == nullptr) throw XMLParseError("Null node", {METADATA_PAIRS});
  std::string name = node->name();
  if (name == "block") {
    std::string type = safeAttr("type", "code");
    BlockType bt =
      type == "root" ? ROOT_BLOCK :
      type == "if" ? IF_BLOCK :
      type == "function" ? FUNCTION_BLOCK : CODE_BLOCK;
    auto block = Node<BlockNode>::make(bt);
    parseChildren(node, block);
    return block;
  } else if (name == "return") {
    auto retNode = Node<ReturnNode>::make();
    auto val = node->first_node("expr");
    if (val != nullptr) retNode->setValue(Node<ExpressionNode>::dynPtrCast(parseXMLNode(val)));
    return retNode;
  } else if (name == "expr") {
    TokenType tokenType = TT::findByPrettyName(requiredAttr("type"));
    std::string data = requiredAttr("value");
    std::unique_ptr<Token> content;
    if (tokenType == TT::OPERATOR) {
      content = std::make_unique<Token>(tokenType, Operator::find(data), defaultTrace);
    } else {
      content = std::make_unique<Token>(tokenType, data, defaultTrace);
    }
    auto expr = Node<ExpressionNode>::make(*content);
    parseChildren(node, expr);
    return expr;
  } else if (name == "decl") {
    Node<DeclarationNode>::Link decl;
    std::string ident = requiredAttr("ident");
    bool isDynamic = boolAttr("dynamic");
    if (isDynamic) {
      decl = Node<DeclarationNode>::make(ident, TypeList {});
    } else {
      std::string tlValue = requiredAttr("types");
      auto vec = split(tlValue, ' ');
      decl = Node<DeclarationNode>::make(ident, TypeList(ALL(vec)));
    }
    auto expr = node->first_node("expr");
    if (expr != nullptr) {
      decl->setInit(Node<ExpressionNode>::dynPtrCast(parseXMLNode(expr)));
    }
    return decl;
  } else if (name == "branch") {
    auto branch = Node<BranchNode>::make();
    auto cond = node->first_node();
    if (cond == nullptr) throw XMLParseError("Missing condition in branch", {METADATA_PAIRS});
    branch->setCondition(Node<ExpressionNode>::dynPtrCast(parseXMLNode(cond)));
    auto success = cond->next_sibling();
    if (success == nullptr) throw XMLParseError("Missing success node in branch", {METADATA_PAIRS});
    branch->setSuccessBlock(Node<BlockNode>::dynPtrCast(parseXMLNode(success)));
    auto blockFailiure = success->next_sibling("block");
    if (blockFailiure != nullptr) {
      branch->setFailiureBlock(Node<BlockNode>::dynPtrCast(parseXMLNode(blockFailiure)));
    }
    auto branchFailiure = success->next_sibling("branch");
    if (branchFailiure != nullptr) {
      branch->setFailiureBlock(Node<BranchNode>::dynPtrCast(parseXMLNode(branchFailiure)));
    }
    return branch;
  } else if (name == "loop") {
    auto loop = Node<LoopNode>::make();
    auto init = node->first_node("loop_init");
    if (init != nullptr) {
      loop->setInit(Node<DeclarationNode>::dynPtrCast(parseXMLNode(init)));
    }
    auto cond = node->first_node("loop_condition");
    if (cond != nullptr) {
      loop->setCondition(Node<ExpressionNode>::dynPtrCast(parseXMLNode(cond)));
    }
    auto update = node->first_node("loop_update");
    if (update != nullptr) {
      loop->setUpdate(Node<ExpressionNode>::dynPtrCast(parseXMLNode(update)));
    }
    auto code = node->first_node("block");
    if (code != nullptr) {
      loop->setCode(Node<BlockNode>::dynPtrCast(parseXMLNode(code)));
    }
    return loop;
  } else if (name == "loop_init" || name == "loop_condition" || name == "loop_update") {
    return parseXMLNode(node->first_node());
  } else if (name == "break") {
    return Node<BreakLoopNode>::make();
  } else if (name == "function") {
    std::string ident = safeAttr("ident");
    bool isForeign = boolAttr("foreign");
    auto n = Node<FunctionNode>::make(ident, FunctionSignature(funRet(), funArgs()), isForeign);
    funBlock(n);
    if (isForeign && ident.empty()) throw XMLParseError("Can't have anonymous foreign function", {METADATA_PAIRS});
    return n;
  } else if (name == "type") {
    std::string typeName = requiredAttr("name");
    std::vector<std::string> inheritTypes = split(safeAttr("inherits"), ' ');
    auto typeNode = Node<TypeNode>::make(typeName, TypeList(ALL(inheritTypes)));
    parseChildren(node, typeNode);
    return typeNode;
  } else if (name == "member") {
    std::string ident = requiredAttr("ident");
    std::vector<std::string> types = split(safeAttr("types"), ' ');
    auto member = Node<MemberNode>::make(ident, TypeList(ALL(types)), boolAttr("static"), getVisibility());
    auto init = node->first_node("expr");
    if (init != nullptr) {
      member->setInit(Node<ExpressionNode>::staticPtrCast(parseXMLNode(init)));
    }
    return member;
  } else if (name == "method") {
    std::string ident = safeAttr("ident");
    bool isForeign = boolAttr("foreign");
    auto method = Node<MethodNode>::make(ident, FunctionSignature(funRet(), funArgs()), getVisibility(), boolAttr("static"), isForeign);
    funBlock(method);
    if (isForeign && ident.empty()) throw XMLParseError("Can't have anonymous foreign method", {METADATA_PAIRS});
    return method;
  } else if (name == "constructor") {
    auto constructor = Node<ConstructorNode>::make(funArgs(), getVisibility());
    funBlock(constructor);
    return constructor;
  }
  throw XMLParseError("Unknown type of node", {METADATA_PAIRS, {"node name", name}});
}

XMLParseError::XMLParseError(std::string msg, ErrorData data):
  InternalError("XMLParseError", msg, data) {}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkRenderWindowInteractor.hh
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

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

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

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

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

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

=========================================================================*/
// .NAME vtkRenderWindowInteractor - provide event driven interface to rendering window
// .SECTION Description

// vtkRenderWindowInteractor is a convenience object that provides event
// bindings to common graphics functions. For example, camera
// zoom-in/zoom-out, pan, rotate, resetting; picking of actors, points,
// or cells; switching in/out of stereo mode; property changes such as
// wireframe and surface; and a toggle to force the light to be placed at
// camera viewpoint (pointing in view direction).

// .SECTION Event Bindings
// Specific devices have different camera bindings. The bindings are on both
// mouse events as well as keyboard presses. See vtkXInteractor and
// vtkWin32Interactor for specific information.

// .SECTION see also
// vtkXRenderWindowInteractor vtkPicker

#ifndef __vtkRenderWindowInteractor_h
#define __vtkRenderWindowInteractor_h

#include "vtkRenderWindow.hh"
#include "vtkCamera.hh"
#include "vtkLight.hh"
#include "vtkPicker.hh"
#include "vtkPolyMapper.hh"
#include "vtkOutlineSource.hh"

class vtkRenderWindowInteractor : public vtkObject
{
public:
  vtkRenderWindowInteractor();
  ~vtkRenderWindowInteractor();
  char *GetClassName() {return "vtkRenderWindowInteractor";};
  void PrintSelf(ostream& os, vtkIndent indent);

  virtual void Initialize() = 0;
  virtual void Start() = 0;

  // Description:
  // Set/Get the rendering window being controlled by this object.
  vtkSetObjectMacro(RenderWindow,vtkRenderWindow);
  vtkGetObjectMacro(RenderWindow,vtkRenderWindow);

  // Description:
  // Turn on/off the automatic repositioning of lights as the camera moves.
  vtkSetMacro(LightFollowCamera,int);
  vtkGetMacro(LightFollowCamera,int);
  vtkBooleanMacro(LightFollowCamera,int);

  // Description:
  // Set/Get the desired update rate. This is use dby vtkLODActors to tell
  // them how quickly they need to render.  This update is in effect only
  // when the camera is being rotated, or zoomed.  When the interactor is
  // still the StillUpdateRate is used instead. A value of zero indicates
  // that the update rate is unimportant. (i.e. take as long as you want)
  vtkSetMacro(DesiredUpdateRate,float);
  vtkGetMacro(DesiredUpdateRate,float);

  // Description:
  // Set/Get the desired update rate when movement has stopped.
  // See the SetDesiredUpdateRate method.
  vtkSetMacro(StillUpdateRate,float);
  vtkGetMacro(StillUpdateRate,float);

  // Description:
  // See whether interactor has been initialized yet.
  vtkGetMacro(Initialized,int);

  // Description:
  // When an event occurs we must determine which Renderer the event
  // occured within since one RenderWindow may contain multiple
  // renderers. We also need to know what camera to operate on.
  // This is just the ActiveCamera of the poked renderer.
  void FindPokedCamera(int,int);
  void FindPokedRenderer(int,int);

  virtual void HighlightActor(vtkActor *actor);

  void SetStartPickMethod(void (*f)(void *), void *arg);
  void SetStartPickMethodArgDelete(void (*f)(void *));
  void SetEndPickMethod(void (*f)(void *), void *arg);
  void SetEndPickMethodArgDelete(void (*f)(void *));

  void SetPicker(vtkPicker *picker);
  void SetPicker(vtkPicker& picker) {this->SetPicker(&picker);};

  // Description:
  // Get the object used to perform pick operations.
  vtkGetObjectMacro(Picker,vtkPicker);

  // Description:
  // Create default picker. Used to create one when none is specified.
  virtual vtkPicker *CreateDefaultPicker();

  void SetUserMethod(void (*f)(void *), void *arg);
  void SetUserMethodArgDelete(void (*f)(void *));

protected:
  vtkRenderWindow *RenderWindow;
  vtkCamera   *CurrentCamera;
  vtkLight    *CurrentLight;
  vtkRenderer *CurrentRenderer;
  int   LightFollowCamera;
  float Center[2];
  float DeltaAzimuth;
  float DeltaElevation;
  int   Size[2];
  int   State;
  float FocalDepth;
  int   Initialized;
  float DesiredUpdateRate;
  float StillUpdateRate;

  // for picking actors
  vtkPicker *Picker;
  int SelfCreatedPicker;
  vtkOutlineSource Outline;
  vtkPolyMapper OutlineMapper;
  vtkActor *OutlineActor;
  vtkRenderer *PickedRenderer;
  vtkActor *CurrentActor;

  // methods called prior to and after picking
  void (*StartPickMethod)(void *);
  void (*StartPickMethodArgDelete)(void *);
  void *StartPickMethodArg;
  void (*EndPickMethod)(void *);
  void (*EndPickMethodArgDelete)(void *);
  void *EndPickMethodArg;
  void (*UserMethod)(void *);
  void (*UserMethodArgDelete)(void *);
  void *UserMethodArg;

};

#endif
<commit_msg>*** empty log message ***<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkRenderWindowInteractor.hh
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

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

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

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

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

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

=========================================================================*/
// .NAME vtkRenderWindowInteractor - provide event driven interface to rendering window
// .SECTION Description

// vtkRenderWindowInteractor is a convenience object that provides event
// bindings to common graphics functions. For example, camera
// zoom-in/zoom-out, pan, rotate, resetting; picking of actors, points,
// or cells; switching in/out of stereo mode; property changes such as
// wireframe and surface; and a toggle to force the light to be placed at
// camera viewpoint (pointing in view direction).

// .SECTION Event Bindings
// Specific devices have different camera bindings. The bindings are on both
// mouse events as well as keyboard presses. See vtkXRenderWindowInteractor and
// vtkWin32RenderWindowInteractor for specific information.

// .SECTION see also
// vtkXRenderWindowInteractor vtkWinRenderWindowInteractor vtkPicker

#ifndef __vtkRenderWindowInteractor_h
#define __vtkRenderWindowInteractor_h

#include "vtkRenderWindow.hh"
#include "vtkCamera.hh"
#include "vtkLight.hh"
#include "vtkPicker.hh"
#include "vtkPolyMapper.hh"
#include "vtkOutlineSource.hh"

class vtkRenderWindowInteractor : public vtkObject
{
public:
  vtkRenderWindowInteractor();
  ~vtkRenderWindowInteractor();
  char *GetClassName() {return "vtkRenderWindowInteractor";};
  void PrintSelf(ostream& os, vtkIndent indent);

  virtual void Initialize() = 0;
  virtual void Start() = 0;

  // Description:
  // Set/Get the rendering window being controlled by this object.
  vtkSetObjectMacro(RenderWindow,vtkRenderWindow);
  vtkGetObjectMacro(RenderWindow,vtkRenderWindow);

  // Description:
  // Turn on/off the automatic repositioning of lights as the camera moves.
  vtkSetMacro(LightFollowCamera,int);
  vtkGetMacro(LightFollowCamera,int);
  vtkBooleanMacro(LightFollowCamera,int);

  // Description:
  // Set/Get the desired update rate. This is use dby vtkLODActors to tell
  // them how quickly they need to render.  This update is in effect only
  // when the camera is being rotated, or zoomed.  When the interactor is
  // still the StillUpdateRate is used instead. A value of zero indicates
  // that the update rate is unimportant. (i.e. take as long as you want)
  vtkSetMacro(DesiredUpdateRate,float);
  vtkGetMacro(DesiredUpdateRate,float);

  // Description:
  // Set/Get the desired update rate when movement has stopped.
  // See the SetDesiredUpdateRate method.
  vtkSetMacro(StillUpdateRate,float);
  vtkGetMacro(StillUpdateRate,float);

  // Description:
  // See whether interactor has been initialized yet.
  vtkGetMacro(Initialized,int);

  // Description:
  // When an event occurs we must determine which Renderer the event
  // occured within since one RenderWindow may contain multiple
  // renderers. We also need to know what camera to operate on.
  // This is just the ActiveCamera of the poked renderer.
  void FindPokedCamera(int,int);
  void FindPokedRenderer(int,int);

  virtual void HighlightActor(vtkActor *actor);

  void SetStartPickMethod(void (*f)(void *), void *arg);
  void SetStartPickMethodArgDelete(void (*f)(void *));
  void SetEndPickMethod(void (*f)(void *), void *arg);
  void SetEndPickMethodArgDelete(void (*f)(void *));

  void SetPicker(vtkPicker *picker);
  void SetPicker(vtkPicker& picker) {this->SetPicker(&picker);};

  // Description:
  // Get the object used to perform pick operations.
  vtkGetObjectMacro(Picker,vtkPicker);

  // Description:
  // Create default picker. Used to create one when none is specified.
  virtual vtkPicker *CreateDefaultPicker();

  void SetUserMethod(void (*f)(void *), void *arg);
  void SetUserMethodArgDelete(void (*f)(void *));

protected:
  vtkRenderWindow *RenderWindow;
  vtkCamera   *CurrentCamera;
  vtkLight    *CurrentLight;
  vtkRenderer *CurrentRenderer;
  int   LightFollowCamera;
  float Center[2];
  float DeltaAzimuth;
  float DeltaElevation;
  int   Size[2];
  int   State;
  float FocalDepth;
  int   Initialized;
  float DesiredUpdateRate;
  float StillUpdateRate;

  // for picking actors
  vtkPicker *Picker;
  int SelfCreatedPicker;
  vtkOutlineSource Outline;
  vtkPolyMapper OutlineMapper;
  vtkActor *OutlineActor;
  vtkRenderer *PickedRenderer;
  vtkActor *CurrentActor;

  // methods called prior to and after picking
  void (*StartPickMethod)(void *);
  void (*StartPickMethodArgDelete)(void *);
  void *StartPickMethodArg;
  void (*EndPickMethod)(void *);
  void (*EndPickMethodArgDelete)(void *);
  void *EndPickMethodArg;
  void (*UserMethod)(void *);
  void (*UserMethodArgDelete)(void *);
  void *UserMethodArg;

};

#endif
<|endoftext|>