<commit_before>/*******************************************************************************************/
/* The MIT License (MIT)                                                                   */
/*                                                                                */
/* Copyright (c) 2014 - Marina High School FIRST Robotics Team 4276 (Huntington Beach, CA) */
/*                                                                                */
/* Permission is hereby granted, free of charge, to any person obtaining a copy            */
/* of this software and associated documentation files (the "Software"), to deal           */
/* in the Software without restriction, including without limitation the rights            */
/* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell               */
/* copies of the Software, and to permit persons to whom the Software is                   */
/* furnished to do so, subject to the following conditions:                                */
/*                                                                                */
/* The above copyright notice and this permission notice shall be included in              */
/* all copies or substantial portions of the Software.                                     */
/*                                                                                */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR              */
/* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,                */

/* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE             */
/* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER                  */
/* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,           */
/* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN               */
/* THE SOFTWARE.                                                                           */
/*******************************************************************************************/

/*******************************************************************************************/
/* We are a high school robotics team and always in need of financial support.             */
/* If you use this software for commercial purposes please return the favor and donate     */
/* (tax free) to "Marina High School Educational Foundation"  (Huntington Beach, CA)       */
/*******************************************************************************************/

#include <stdio.h>
#include <string>
#include <signal.h>
#include <unistd.h>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/features2d/features2d.hpp>

#include "CToteRectangle.h"
#include "CTargetInfo.h"
#include "CVideoFrame.h"
#include "CVideoFrameQueue.h"
#include "CConnectionServer.h"
#include "CGpioLed.h"
#include "CToteDetector.h"
#include "CTestMonitor.h"
#include "CFrameGrinder.h"
#include "dbgMsg.h"
#include "viking_cv_version.h"

CToteDetector::CToteDetector()
{
}

CToteDetector::CToteDetector(const CToteDetector& orig)
{
}

CToteDetector::~CToteDetector()
{
}

void CToteDetector::init()
{
    m_tolerancePercentForRadius = 0.20;
}

void CToteDetector::detectBlobs(CVideoFrame * pFrame, CFrameGrinder* pFrameGrinder)
{
    try
    {
        static struct timespec timeLastCameraFrame = {0};
        static struct timespec timeNow = {0};
        cv::Mat img_hsv, gray_blob, binary_blob, binary_blob_8u;
        static int iCount = 0;

        int timeSinceLastCameraFrameMilliseconds = (int) CTestMonitor::getDeltaTimeMilliseconds(
                timeLastCameraFrame,
                pFrame->m_timeAddedToQueue[(int) CVideoFrame::FRAME_QUEUE_WAIT_FOR_BLOB_DETECT]);
        timeLastCameraFrame = pFrame->m_timeAddedToQueue[(int) CVideoFrame::FRAME_QUEUE_WAIT_FOR_BLOB_DETECT];

        // RBG is flawed as a way to filter based on color because the brightness is combined
        // with the color info.
        // Not so with HSV, where Hue and Saturation are maintained separately
        // OpenCV has a handy conversion from RGB to HSV
        cv::cvtColor(pFrame->m_frame, img_hsv, CV_BGR2HSV);

        // Filter out all but Gray hue

#ifdef COLORFILTER_ZOOKS_CLASSROOM_LIFECAM
        cv::inRange(img_hsv, cv::Scalar(30, 15, 32), cv::Scalar(80, 220, 220), gray_blob);
#endif

#ifdef COLORFILTER_MARINA_HALLWAY_LIFECAM
        cv::inRange(img_hsv, cv::Scalar(30, 0, 90), cv::Scalar(220, 80, 160), gray_blob);
#endif

#ifdef COLORFILTER_MARINA_HALLWAY_LOGITECH
        cv::inRange(img_hsv, cv::Scalar(30, 0, 120), cv::Scalar(220, 80, 160), gray_blob);
#endif

#ifdef COLORFILTER_LA_SPORTS_ARENA_LOGITECH
        cv::inRange(img_hsv, cv::Scalar(15, 0, 40), cv::Scalar(55, 70, 200), gray_blob);
#endif
        iCount++;
        //if ((iCount % 17) == 0)
        {
            pFrameGrinder->m_testMonitor.saveFrameToJpeg(gray_blob);
        }

        // make a kernel of 4x4, all 1's
        cv::Mat kernel = cv::Mat::ones(cv::Size(2, 2), CV_8U);
        cv::erode(gray_blob, gray_blob, kernel);

         //Find the contours. Use the contourOutput Mat so the original image doesn't get overwritten
        std::vector<std::vector<cv::Point> > grayContours;
        try
        {
            cv::findContours(gray_blob, grayContours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE );
        }
        catch( cv::Exception& e )
        {
            const char* err_msg = e.what();
            dbgMsg_s(err_msg);
        }

        //const cv::Scalar colorGreen = cv::Scalar(0, 255, 0);
        //for (int i = 0; i < grayContours.size(); i++){
        //    cv::drawContours(pFrame->m_frame, grayContours, i, colorGreen, 1, 8);
        //}
        //pFrameGrinder->m_testMonitor.saveFrameToJpeg(pFrame->m_frame);

        CToteRectangle bestToteRectangleGray;
        float toteDirectionDegrees = 0.0;
        float toteAngleDegrees = 0.0;
        float distanceToToteCenterInches = 0.0;
        bool isGrayToteFound = false;
#ifdef DETECT_LARGEST_BLOB_NO_FILTER_BASED_ON_SIZE
        isGrayToteFound = filterContoursToFindLargestBlob(grayContours, bestToteRectangleGray,
                                                           toteDirectionDegrees, toteAngleDegrees, distanceToToteCenterInches);

#ifdef DISPLAY_CALIBRATION_INFO
        printf("viking_cv version %d.%d.%d", VERSION_YEAR, VERSION_INTERFACE, VERSION_BUILD);
        if (isGrayToteFound)
        {
            printf("   NearFar_X: %d    LeftRight_Y: %d    Radius  %02f\r",
                    (int) bestToteRectangleGray.m_ptCenter.x,
                    (int) bestToteRectangleGray.m_ptCenter.y,
                    bestToteRectangleGray.m_radius);
        }
        else
        {
            printf("   Gray rectangle *NOT* found\r");
        }
#endif

#else
        isGrayToteFound = filterContoursToFindToteBySize(grayContours, bestToteRectangleGray, angleToBlueToteDegrees, offsetFromCenterlineToToteCenterToteFeet);
#endif

        CTestMonitor::getTicks(&timeNow);
        int timeLatencyThisCameraFrameMilliseconds = (int) CTestMonitor::getDeltaTimeMilliseconds(
                pFrame->m_timeAddedToQueue[(int) CVideoFrame::FRAME_QUEUE_WAIT_FOR_BLOB_DETECT],
                timeNow);

        pFrame->m_targetInfo.updateTargetInfo(
                timeSinceLastCameraFrameMilliseconds, timeLatencyThisCameraFrameMilliseconds,
                isGrayToteFound, toteDirectionDegrees, toteAngleDegrees, distanceToToteCenterInches);

        pFrame->updateAnnotationInfo(bestToteRectangleGray);

        m_gpioLed.setGreenLED(isGrayToteFound, pFrame->m_timeRemovedFromQueue[(int) CVideoFrame::FRAME_QUEUE_WAIT_FOR_BLOB_DETECT]);
    }
    catch (...)
    {
    }
}

bool CToteDetector::filterContoursToFindLargestBlob(
        const std::vector<std::vector<cv::Point> >& listContours,
        CToteRectangle& bestToteRectangle,
        float& toteDirectionDegrees,
        float& toteAngleDegrees,
        float& distanceToToteCenterInches)
{
    const cv::Point2f robotCenter(VIEW_PIXEL_X_WIDTH + (PIXEL_OFFSET_FROM_CENTERLINE_TO_CAMERA),
            VIEW_PIXEL_Y_HEIGHT + PIXEL_OFFSET_FROM_ROBOT_CENTER_TO_BOTTOM_OF_VIEW);

    bool isToteFound = false;
    bestToteRectangle.init();
    toteDirectionDegrees = -999.0;
    toteAngleDegrees = -999.0;
    distanceToToteCenterInches = -1.0;

    unsigned int i = 0;
    CToteRectangle tempToteRectangle;
    double aspectRatio, diff, area, predict, max;
    cv::RotatedRect tempRect, vertRect, horizRect;
    std::vector<CToteRectangle> listPossibleToteRectangle;
    std::vector<cv::Point> contours_poly;
    max = 0.0;
    for (i = 0; i < listContours.size(); i++)
    {
        tempRect = cv::minAreaRect(cv::Mat(listContours[i]));
        area = tempRect.size.width * tempRect.size.height;
        if ((area > 6500.0) && (area < 8500.0))
        {
            if(max < area)
            {
                max = area;
                isToteFound = true;
                bestToteRectangle = tempRect;
            }
        }
    }
    if (isToteFound)
    {
        cv::Point2f diff = robotCenter - bestToteRectangle.center;
        distanceToToteCenterInches = cv::sqrt(diff.x*diff.x + diff.y*diff.y);
        distanceToToteCenterInches *= INCHES_PER_PIXEL;

        toteDirectionDegrees = atan(diff.x/diff.y) * DEGREES_PER_RADIAN;

        toteAngleDegrees = bestToteRectangle.angle;
    }
    return isToteFound;
}
<commit_msg>REmove debug code<commit_after>/*******************************************************************************************/
/* The MIT License (MIT)                                                                   */
/*                                                                                */
/* Copyright (c) 2014 - Marina High School FIRST Robotics Team 4276 (Huntington Beach, CA) */
/*                                                                                */
/* Permission is hereby granted, free of charge, to any person obtaining a copy            */
/* of this software and associated documentation files (the "Software"), to deal           */
/* in the Software without restriction, including without limitation the rights            */
/* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell               */
/* copies of the Software, and to permit persons to whom the Software is                   */
/* furnished to do so, subject to the following conditions:                                */
/*                                                                                */
/* The above copyright notice and this permission notice shall be included in              */
/* all copies or substantial portions of the Software.                                     */
/*                                                                                */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR              */
/* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,                */

/* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE             */
/* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER                  */
/* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,           */
/* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN               */
/* THE SOFTWARE.                                                                           */
/*******************************************************************************************/

/*******************************************************************************************/
/* We are a high school robotics team and always in need of financial support.             */
/* If you use this software for commercial purposes please return the favor and donate     */
/* (tax free) to "Marina High School Educational Foundation"  (Huntington Beach, CA)       */
/*******************************************************************************************/

#include <stdio.h>
#include <string>
#include <signal.h>
#include <unistd.h>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/features2d/features2d.hpp>

#include "CToteRectangle.h"
#include "CTargetInfo.h"
#include "CVideoFrame.h"
#include "CVideoFrameQueue.h"
#include "CConnectionServer.h"
#include "CGpioLed.h"
#include "CToteDetector.h"
#include "CTestMonitor.h"
#include "CFrameGrinder.h"
#include "dbgMsg.h"
#include "viking_cv_version.h"

CToteDetector::CToteDetector()
{
}

CToteDetector::CToteDetector(const CToteDetector& orig)
{
}

CToteDetector::~CToteDetector()
{
}

void CToteDetector::init()
{
    m_tolerancePercentForRadius = 0.20;
}

void CToteDetector::detectBlobs(CVideoFrame * pFrame, CFrameGrinder* pFrameGrinder)
{
    try
    {
        static struct timespec timeLastCameraFrame = {0};
        static struct timespec timeNow = {0};
        cv::Mat img_hsv, gray_blob, binary_blob, binary_blob_8u;
        static int iCount = 0;

        int timeSinceLastCameraFrameMilliseconds = (int) CTestMonitor::getDeltaTimeMilliseconds(
                timeLastCameraFrame,
                pFrame->m_timeAddedToQueue[(int) CVideoFrame::FRAME_QUEUE_WAIT_FOR_BLOB_DETECT]);
        timeLastCameraFrame = pFrame->m_timeAddedToQueue[(int) CVideoFrame::FRAME_QUEUE_WAIT_FOR_BLOB_DETECT];

        // RBG is flawed as a way to filter based on color because the brightness is combined
        // with the color info.
        // Not so with HSV, where Hue and Saturation are maintained separately
        // OpenCV has a handy conversion from RGB to HSV
        cv::cvtColor(pFrame->m_frame, img_hsv, CV_BGR2HSV);

        // Filter out all but Gray hue

#ifdef COLORFILTER_ZOOKS_CLASSROOM_LIFECAM
        cv::inRange(img_hsv, cv::Scalar(30, 15, 32), cv::Scalar(80, 220, 220), gray_blob);
#endif

#ifdef COLORFILTER_MARINA_HALLWAY_LIFECAM
        cv::inRange(img_hsv, cv::Scalar(30, 0, 90), cv::Scalar(220, 80, 160), gray_blob);
#endif

#ifdef COLORFILTER_MARINA_HALLWAY_LOGITECH
        cv::inRange(img_hsv, cv::Scalar(30, 0, 120), cv::Scalar(220, 80, 160), gray_blob);
#endif

#ifdef COLORFILTER_LA_SPORTS_ARENA_LOGITECH
        cv::inRange(img_hsv, cv::Scalar(15, 0, 40), cv::Scalar(55, 70, 200), gray_blob);
#endif
        iCount++;
        if ((iCount % 17) == 0)
        {
            pFrameGrinder->m_testMonitor.saveFrameToJpeg(gray_blob);
        }

        // make a kernel of 4x4, all 1's
        cv::Mat kernel = cv::Mat::ones(cv::Size(2, 2), CV_8U);
        cv::erode(gray_blob, gray_blob, kernel);

         //Find the contours. Use the contourOutput Mat so the original image doesn't get overwritten
        std::vector<std::vector<cv::Point> > grayContours;
        try
        {
            cv::findContours(gray_blob, grayContours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE );
        }
        catch( cv::Exception& e )
        {
            const char* err_msg = e.what();
            dbgMsg_s(err_msg);
        }

        //const cv::Scalar colorGreen = cv::Scalar(0, 255, 0);
        //for (int i = 0; i < grayContours.size(); i++){
        //    cv::drawContours(pFrame->m_frame, grayContours, i, colorGreen, 1, 8);
        //}
        //pFrameGrinder->m_testMonitor.saveFrameToJpeg(pFrame->m_frame);

        CToteRectangle bestToteRectangleGray;
        float toteDirectionDegrees = 0.0;
        float toteAngleDegrees = 0.0;
        float distanceToToteCenterInches = 0.0;
        bool isGrayToteFound = false;
#ifdef DETECT_LARGEST_BLOB_NO_FILTER_BASED_ON_SIZE
        isGrayToteFound = filterContoursToFindLargestBlob(grayContours, bestToteRectangleGray,
                                                           toteDirectionDegrees, toteAngleDegrees, distanceToToteCenterInches);

#ifdef DISPLAY_CALIBRATION_INFO
        printf("viking_cv version %d.%d.%d", VERSION_YEAR, VERSION_INTERFACE, VERSION_BUILD);
        if (isGrayToteFound)
        {
            printf("   NearFar_X: %d    LeftRight_Y: %d    Radius  %02f\r",
                    (int) bestToteRectangleGray.m_ptCenter.x,
                    (int) bestToteRectangleGray.m_ptCenter.y,
                    bestToteRectangleGray.m_radius);
        }
        else
        {
            printf("   Gray rectangle *NOT* found\r");
        }
#endif

#else
        isGrayToteFound = filterContoursToFindToteBySize(grayContours, bestToteRectangleGray, angleToBlueToteDegrees, offsetFromCenterlineToToteCenterToteFeet);
#endif

        CTestMonitor::getTicks(&timeNow);
        int timeLatencyThisCameraFrameMilliseconds = (int) CTestMonitor::getDeltaTimeMilliseconds(
                pFrame->m_timeAddedToQueue[(int) CVideoFrame::FRAME_QUEUE_WAIT_FOR_BLOB_DETECT],
                timeNow);

        pFrame->m_targetInfo.updateTargetInfo(
                timeSinceLastCameraFrameMilliseconds, timeLatencyThisCameraFrameMilliseconds,
                isGrayToteFound, toteDirectionDegrees, toteAngleDegrees, distanceToToteCenterInches);

        pFrame->updateAnnotationInfo(bestToteRectangleGray);

        m_gpioLed.setGreenLED(isGrayToteFound, pFrame->m_timeRemovedFromQueue[(int) CVideoFrame::FRAME_QUEUE_WAIT_FOR_BLOB_DETECT]);
    }
    catch (...)
    {
    }
}

bool CToteDetector::filterContoursToFindLargestBlob(
        const std::vector<std::vector<cv::Point> >& listContours,
        CToteRectangle& bestToteRectangle,
        float& toteDirectionDegrees,
        float& toteAngleDegrees,
        float& distanceToToteCenterInches)
{
    const cv::Point2f robotCenter(VIEW_PIXEL_X_WIDTH + (PIXEL_OFFSET_FROM_CENTERLINE_TO_CAMERA),
            VIEW_PIXEL_Y_HEIGHT + PIXEL_OFFSET_FROM_ROBOT_CENTER_TO_BOTTOM_OF_VIEW);

    bool isToteFound = false;
    bestToteRectangle.init();
    toteDirectionDegrees = -999.0;
    toteAngleDegrees = -999.0;
    distanceToToteCenterInches = -1.0;

    unsigned int i = 0;
    CToteRectangle tempToteRectangle;
    double aspectRatio, diff, area, predict, max;
    cv::RotatedRect tempRect, vertRect, horizRect;
    std::vector<CToteRectangle> listPossibleToteRectangle;
    std::vector<cv::Point> contours_poly;
    max = 0.0;
    for (i = 0; i < listContours.size(); i++)
    {
        tempRect = cv::minAreaRect(cv::Mat(listContours[i]));
        area = tempRect.size.width * tempRect.size.height;
        if ((area > 6500.0) && (area < 8500.0))
        {
            if(max < area)
            {
                max = area;
                isToteFound = true;
                bestToteRectangle = tempRect;
            }
        }
    }
    if (isToteFound)
    {
        cv::Point2f diff = robotCenter - bestToteRectangle.center;
        distanceToToteCenterInches = cv::sqrt(diff.x*diff.x + diff.y*diff.y);
        distanceToToteCenterInches *= INCHES_PER_PIXEL;

        toteDirectionDegrees = atan(diff.x/diff.y) * DEGREES_PER_RADIAN;

        toteAngleDegrees = bestToteRectangle.angle;
    }
    return isToteFound;
}
<|endoftext|>


<commit_before>/*************************************************************************
> File Name: dynamic_cast.cpp
> Author: Chan-Ho Chris Ohk
> E-mail: utilForever@gmail.com
> Created Time: 2015/7/15
> Personal Blog: https://github.com/utilForever
> References: http://prostars.net/55
************************************************************************/
#include <iostream>

class Base
{
public:
	virtual void print() { std::cout << "Base" << std::endl; }
};

class Derived : public Base
{
public:
	virtual void print() { std::cout << "Derived" << std::endl; }
};

int main()
{
	Base* base1 = new Base;
	Base* base2 = new Derived;
	Derived* derived1 = new Derived;
	Derived* derived2 = nullptr;

	// Compile Error: Can't convert type
	// derived2 = base1;

	// Compile Success: Fail to convert type and return nullptr at run-time
	derived2 = dynamic_cast<Derived*>(base1);
	if (derived2 == nullptr)
		std::cout << "Runtime Error" << std::endl;

	// Compile Error: Can't convert type
	// derived2 = base2;

	// Compile Success: Success to convert type and return Derived* at run-time
	derived2 = dynamic_cast<Derived*>(base2);
	if (derived2)
		derived2->print();

	// Compile Success: Don't need casting in this case
	derived2 = derived1;
}<commit_msg>Repl explanation and code<commit_after>/*************************************************************************
> File Name: dynamic_cast.cpp
> Author: Chan-Ho Chris Ohk
> E-mail: utilForever@gmail.com
> Created Time: 2015/7/15
> Updated Time: 2016/10/29
> Personal Blog: https://github.com/utilForever
> References: http://prostars.net/55
> References: http://en.cppreference.com/w/cpp/language/dynamic_cast
************************************************************************/
#include <iostream>

struct Animal
{
	virtual ~Animal()
	{

	}

	// Must be polymorphic to use runtime-checked dynamic_cast
	virtual void Identify()
	{
		std::cout << "Animal" << std::endl;
	};
};

struct Dog : Animal
{
	void Identify() override
	{
		std::cout << "Dog" << std::endl;
	}
};

struct Bird : Animal
{
	Bird(Animal* a, Dog* d) {
		// Casts during construction (see the call in the constructor of DogBird(mutant?) below)
		dynamic_cast<Bird*>(a); // well-defined: a of type Animal*, Animal base of Bird, results in Bird*
		dynamic_cast<Bird*>(d); // undefined behavior: d has type Dog*, Dog not a base of Bird
	}

	void Identify() override
	{
		std::cout << "Bird" << std::endl;
	}
};

struct DogBird : Dog, Bird
{
	DogBird() : Bird(static_cast<Dog*>(this), this)
	{

	}
};

struct Base
{
	virtual ~Base()
	{

	}
};

struct Derived : Base
{
	virtual void Name()
	{
		std::cout << "My name is Derived!" << std::endl;
	}
};

int main()
{
	// dynamic_cast safely converts pointers and references to classes up, down,
	// and sideways along the inheritance hierarchy.
	// The most derived object (Animal, Dog, Bird)
	DogBird db;
	// db.Identify() is ambiguous call (What is function to call? Dog::Identify()? Bird::Identify()?)
	// db.Identify();
	// Upcast, dynamic_cast may be used, but unnecessary
	Dog& d = db;
	// Prints "Dog"
	d.Identify();
	// Downcast
	DogBird& newDB = dynamic_cast<DogBird&>(d);
	// newDB's type is DogBird.
	// So, newDB.Identify() is ambiguous call (What is function to call? Dog::Identify()? Bird::Identify()?)
	// newDB.Identify();
	// Sidecast
	Bird& newB = dynamic_cast<Bird&>(d);
	// Prints "Bird"
	newB.Identify();
	std::cout << std::endl;

	Base* b1 = new Base;
	// b1 has type Base*, Base not a base of Base.
	// So dynamic_cast fails, and returns nullptr.
	if (Derived* d1 = dynamic_cast<Derived*>(b1))
	{
		std::cout << "Downcast from b1 to d1 successful\n";
		d1->Name();
	}

	// b2 has type Derived*, Derived base of Base.
	// So dynamic_cast successes, and returns Derived*.
	Base* b2 = new Derived;
	if (Derived* d2 = dynamic_cast<Derived*>(b2))
	{
		std::cout << "Downcast from b2 to d2 successful\n";
		d2->Name();
	}

	delete b1;
	delete b2;
}<|endoftext|>


<commit_before>#pragma once

#include "Geometry/R3Element.hpp"
#include "Quantities/Dimensionless.hpp"
#include "Quantities/Quantities.hpp"

namespace principia {
namespace geometry {

// A multivector of rank Rank on a three-dimensional real inner product space
// bearing the dimensionality of Scalar.
// Do not use this type for Rank = 0 (scalar), use the Scalar type directly
// instead.
template<typename Scalar, typename Frame, unsigned int Rank>
struct Multivector;

template<typename Scalar, typename Frame>
class Multivector<Scalar, Frame, 1> {
 public:
  explicit Multivector(R3Element<Scalar> const& coordinates);
  ~Multivector() = default;

  R3Element<Scalar> coordinates() const;

 private:
  R3Element<Scalar> coordinates_;
};

template<typename Scalar, typename Frame>
struct Multivector<Scalar, Frame, 2> {
  explicit Multivector(R3Element<Scalar> const& coordinates);
  ~Multivector() = default;

  R3Element<Scalar> coordinates() const;

 private:
  R3Element<Scalar> coordinates_;
};

template<typename Scalar, typename Frame>
struct Multivector<Scalar, Frame, 3> {
  explicit Multivector(Scalar const& coordinates);
  ~Multivector() = default;

  Scalar coordinates() const;

 private:
  Scalar coordinates_;
};

template<typename Scalar, typename Frame>
using Vector = Multivector<Scalar, Frame, 1>;
template<typename Scalar, typename Frame>
using Bivector = Multivector<Scalar, Frame, 2>;
template<typename Scalar, typename Frame>
using Trivector = Multivector<Scalar, Frame, 3>;

template<typename LScalar, typename RScalar, typename Frame>
quantities::Product<LScalar, RScalar> InnerProduct(
    Vector<LScalar, Frame> const& left,
    Vector<RScalar, Frame> const& right);
template<typename LScalar, typename RScalar, typename Frame>
quantities::Product<LScalar, RScalar> InnerProduct(
    Bivector<LScalar, Frame> const& left,
    Bivector<RScalar, Frame> const& right);
template<typename LScalar, typename RScalar, typename Frame>
quantities::Product<LScalar, RScalar> InnerProduct(
    Trivector<LScalar, Frame> const& left,
    Trivector<RScalar, Frame> const& right);

template<typename LScalar, typename RScalar, typename Frame>
Bivector<quantities::Product<LScalar, RScalar>, Frame> Wedge(
    Vector<LScalar, Frame> const& left,
    Vector<RScalar, Frame> const& right);
template<typename LScalar, typename RScalar, typename Frame>
Trivector<quantities::Product<LScalar, RScalar>, Frame> Wedge(
    Bivector<LScalar, Frame> const& left,
    Vector<RScalar, Frame> const& right);
template<typename LScalar, typename RScalar, typename Frame>
Trivector<quantities::Product<LScalar, RScalar>, Frame> Wedge(
    Vector<LScalar, Frame> const& left,
    Bivector<RScalar, Frame> const& right);

// Lie bracket on V ^ V = so(V).
template<typename LScalar, typename RScalar, typename Frame>
Bivector<quantities::Product<LScalar, RScalar>, Frame> Commutator(
    Bivector<LScalar, Frame> const& left,
    Bivector<RScalar, Frame> const& right);

// Left action of V ^ V = so(V) on V.
template<typename LScalar, typename RScalar, typename Frame>
Vector<quantities::Product<LScalar, RScalar>, Frame> operator*(
    Bivector<LScalar, Frame> const& left,
    Vector<RScalar, Frame> const& right);

// Right action of V ^ V = so(V) on V* = V.
template<typename LScalar, typename RScalar, typename Frame>
Vector<quantities::Product<LScalar, RScalar>, Frame> operator*(
    Vector<LScalar, Frame> const& left,
    Bivector<RScalar, Frame> const& right);

template<typename Scalar, typename Frame, unsigned int Rank>
Multivector<Scalar, Frame, Rank> operator+(
    Multivector<Scalar, Frame, Rank> const& right);
template<typename Scalar, typename Frame, unsigned int Rank>
Multivector<Scalar, Frame, Rank> operator-(
    Multivector<Scalar, Frame, Rank> const& right);

template<typename Scalar, typename Frame, unsigned int Rank>
Multivector<Scalar, Frame, Rank> operator+(
    Multivector<Scalar, Frame, Rank> const& left,
    Multivector<Scalar, Frame, Rank> const& right);
template<typename Scalar, typename Frame, unsigned int Rank>
Multivector<Scalar, Frame, Rank> operator-(
    Multivector<Scalar, Frame, Rank> const& left,
    Multivector<Scalar, Frame, Rank> const& right);

template<typename Scalar, typename Frame, unsigned int Rank>
Multivector<Scalar, Frame, Rank> operator*(
    quantities::Dimensionless const& left,
    Multivector<Scalar, Frame, Rank> const& right);
template<typename Scalar, typename Frame, unsigned int Rank>
Multivector<Scalar, Frame, Rank> operator*(
    Multivector<Scalar, Frame, Rank> const& left,
    quantities::Dimensionless const& right);
template<typename Scalar, typename Frame, unsigned int Rank>
Multivector<Scalar, Frame, Rank> operator/(
    Multivector<Scalar, Frame, Rank> const& left,
    quantities::Dimensionless const& right);

template<typename LDimension, typename RScalar, typename Frame,
         unsigned int Rank>
Multivector<quantities::Product<quantities::Quantity<LDimension>, RScalar>,
            Frame, Rank>
operator*(quantities::Quantity<LDimension> const& left,
          Multivector<RScalar, Frame, Rank> const& right);

template<typename LScalar, typename RDimension, typename Frame,
         unsigned int Rank>
Multivector<quantities::Product<LScalar, quantities::Quantity<RDimension>>,
            Frame, Rank>
operator*(Multivector<LScalar, Frame, Rank> const& left,
          quantities::Quantity<RDimension> const& right);

template<typename LScalar, typename RDimension, typename Frame,
         unsigned int Rank>
Multivector<quantities::Quotient<LScalar, quantities::Quantity<RDimension>>,
            Frame, Rank>
operator/(Multivector<LScalar, Frame, Rank> const& left,
          quantities::Quantity<RDimension> const& right);

template<typename Scalar, typename Frame, unsigned int Rank>
void operator+=(Multivector<Scalar, Frame, Rank>& left,
                Multivector<Scalar, Frame, Rank> const& right);
template<typename Scalar, typename Frame, unsigned int Rank>
void operator-=(Multivector<Scalar, Frame, Rank>& left,
                Multivector<Scalar, Frame, Rank> const& right);
template<typename Scalar, typename Frame, unsigned int Rank>
void operator*=(Multivector<Scalar, Frame, Rank>& left,
                quantities::Dimensionless const& right);
template<typename Scalar, typename Frame, unsigned int Rank>
void operator/=(Multivector<Scalar, Frame, Rank>& left,
                quantities::Dimensionless const& right);

}  // namespace geometry
}  // namespace principia

#include "Geometry/Grassmann-body.hpp"
<commit_msg>Trivector-(Vector|Bivector) multiplication spec.<commit_after>#pragma once

#include "Geometry/R3Element.hpp"
#include "Quantities/Dimensionless.hpp"
#include "Quantities/Quantities.hpp"

namespace principia {
namespace geometry {

// A multivector of rank Rank on a three-dimensional real inner product space
// bearing the dimensionality of Scalar.
// Do not use this type for Rank = 0 (scalar), use the Scalar type directly
// instead.
template<typename Scalar, typename Frame, unsigned int Rank>
struct Multivector;

template<typename Scalar, typename Frame>
class Multivector<Scalar, Frame, 1> {
 public:
  explicit Multivector(R3Element<Scalar> const& coordinates);
  ~Multivector() = default;

  R3Element<Scalar> coordinates() const;

 private:
  R3Element<Scalar> coordinates_;
};

template<typename Scalar, typename Frame>
struct Multivector<Scalar, Frame, 2> {
  explicit Multivector(R3Element<Scalar> const& coordinates);
  ~Multivector() = default;

  R3Element<Scalar> coordinates() const;

 private:
  R3Element<Scalar> coordinates_;
};

template<typename Scalar, typename Frame>
struct Multivector<Scalar, Frame, 3> {
  explicit Multivector(Scalar const& coordinates);
  ~Multivector() = default;

  Scalar coordinates() const;

 private:
  Scalar coordinates_;
};

template<typename Scalar, typename Frame>
using Vector = Multivector<Scalar, Frame, 1>;
template<typename Scalar, typename Frame>
using Bivector = Multivector<Scalar, Frame, 2>;
template<typename Scalar, typename Frame>
using Trivector = Multivector<Scalar, Frame, 3>;

template<typename LScalar, typename RScalar, typename Frame>
quantities::Product<LScalar, RScalar> InnerProduct(
    Vector<LScalar, Frame> const& left,
    Vector<RScalar, Frame> const& right);
template<typename LScalar, typename RScalar, typename Frame>
quantities::Product<LScalar, RScalar> InnerProduct(
    Bivector<LScalar, Frame> const& left,
    Bivector<RScalar, Frame> const& right);
template<typename LScalar, typename RScalar, typename Frame>
quantities::Product<LScalar, RScalar> InnerProduct(
    Trivector<LScalar, Frame> const& left,
    Trivector<RScalar, Frame> const& right);

template<typename LScalar, typename RScalar, typename Frame>
Bivector<quantities::Product<LScalar, RScalar>, Frame> Wedge(
    Vector<LScalar, Frame> const& left,
    Vector<RScalar, Frame> const& right);
template<typename LScalar, typename RScalar, typename Frame>
Trivector<quantities::Product<LScalar, RScalar>, Frame> Wedge(
    Bivector<LScalar, Frame> const& left,
    Vector<RScalar, Frame> const& right);
template<typename LScalar, typename RScalar, typename Frame>
Trivector<quantities::Product<LScalar, RScalar>, Frame> Wedge(
    Vector<LScalar, Frame> const& left,
    Bivector<RScalar, Frame> const& right);

// Lie bracket on V ^ V = so(V).
template<typename LScalar, typename RScalar, typename Frame>
Bivector<quantities::Product<LScalar, RScalar>, Frame> Commutator(
    Bivector<LScalar, Frame> const& left,
    Bivector<RScalar, Frame> const& right);

// Left action of V ^ V = so(V) on V.
template<typename LScalar, typename RScalar, typename Frame>
Vector<quantities::Product<LScalar, RScalar>, Frame> operator*(
    Bivector<LScalar, Frame> const& left,
    Vector<RScalar, Frame> const& right);

// Right action of V ^ V = so(V) on V* = V.
template<typename LScalar, typename RScalar, typename Frame>
Vector<quantities::Product<LScalar, RScalar>, Frame> operator*(
    Vector<LScalar, Frame> const& left,
    Bivector<RScalar, Frame> const& right);

template<typename LScalar, typename RScalar, typename Frame>
Vector<quantities::Product<LScalar, RScalar>, Frame> operator*(
    Bivector<LScalar, Frame> const& left,
    Trivector<RScalar, Frame> const& right);
template<typename LScalar, typename RScalar, typename Frame>
Vector<quantities::Product<LScalar, RScalar>, Frame> operator*(
    Trivector<LScalar, Frame> const& left,
    Bivector<RScalar, Frame> const& right);
template<typename LScalar, typename RScalar, typename Frame>
Bivector<quantities::Product<LScalar, RScalar>, Frame> operator*(
    Vector<LScalar, Frame> const& left,
    Trivector<RScalar, Frame> const& right);
template<typename LScalar, typename RScalar, typename Frame>
Bivector<quantities::Product<LScalar, RScalar>, Frame> operator*(
    Trivector<LScalar, Frame> const& left,
    Vector<RScalar, Frame> const& right);

template<typename Scalar, typename Frame, unsigned int Rank>
Multivector<Scalar, Frame, Rank> operator+(
    Multivector<Scalar, Frame, Rank> const& right);
template<typename Scalar, typename Frame, unsigned int Rank>
Multivector<Scalar, Frame, Rank> operator-(
    Multivector<Scalar, Frame, Rank> const& right);

template<typename Scalar, typename Frame, unsigned int Rank>
Multivector<Scalar, Frame, Rank> operator+(
    Multivector<Scalar, Frame, Rank> const& left,
    Multivector<Scalar, Frame, Rank> const& right);
template<typename Scalar, typename Frame, unsigned int Rank>
Multivector<Scalar, Frame, Rank> operator-(
    Multivector<Scalar, Frame, Rank> const& left,
    Multivector<Scalar, Frame, Rank> const& right);

template<typename Scalar, typename Frame, unsigned int Rank>
Multivector<Scalar, Frame, Rank> operator*(
    quantities::Dimensionless const& left,
    Multivector<Scalar, Frame, Rank> const& right);
template<typename Scalar, typename Frame, unsigned int Rank>
Multivector<Scalar, Frame, Rank> operator*(
    Multivector<Scalar, Frame, Rank> const& left,
    quantities::Dimensionless const& right);
template<typename Scalar, typename Frame, unsigned int Rank>
Multivector<Scalar, Frame, Rank> operator/(
    Multivector<Scalar, Frame, Rank> const& left,
    quantities::Dimensionless const& right);

template<typename LDimension, typename RScalar, typename Frame,
         unsigned int Rank>
Multivector<quantities::Product<quantities::Quantity<LDimension>, RScalar>,
            Frame, Rank>
operator*(quantities::Quantity<LDimension> const& left,
          Multivector<RScalar, Frame, Rank> const& right);

template<typename LScalar, typename RDimension, typename Frame,
         unsigned int Rank>
Multivector<quantities::Product<LScalar, quantities::Quantity<RDimension>>,
            Frame, Rank>
operator*(Multivector<LScalar, Frame, Rank> const& left,
          quantities::Quantity<RDimension> const& right);

template<typename LScalar, typename RDimension, typename Frame,
         unsigned int Rank>
Multivector<quantities::Quotient<LScalar, quantities::Quantity<RDimension>>,
            Frame, Rank>
operator/(Multivector<LScalar, Frame, Rank> const& left,
          quantities::Quantity<RDimension> const& right);

template<typename Scalar, typename Frame, unsigned int Rank>
void operator+=(Multivector<Scalar, Frame, Rank>& left,
                Multivector<Scalar, Frame, Rank> const& right);
template<typename Scalar, typename Frame, unsigned int Rank>
void operator-=(Multivector<Scalar, Frame, Rank>& left,
                Multivector<Scalar, Frame, Rank> const& right);
template<typename Scalar, typename Frame, unsigned int Rank>
void operator*=(Multivector<Scalar, Frame, Rank>& left,
                quantities::Dimensionless const& right);
template<typename Scalar, typename Frame, unsigned int Rank>
void operator/=(Multivector<Scalar, Frame, Rank>& left,
                quantities::Dimensionless const& right);

}  // namespace geometry
}  // namespace principia

#include "Geometry/Grassmann-body.hpp"
<|endoftext|>


<commit_before>/*
 * client_proc.cpp
 *
 * This is the client process
 */
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>
#include <iostream>
#include <vector>

#include "rpc.h"
#include "sck_stream.h"
#include "message_protocol.h"
#include "utility.h";
#include "response_codes.h"

using namespace std;

class ClientProcess {
  private:
    static ClientProcess* singleton;
    int binderSockFd;
    char* BINDER_ADDRESS;
    char* BINDER_PORT;

    ServerPortCombo* locationForCall = NULL;

  protected:
    ClientProcess() { // called only once in the ctr
      BINDER_ADDRESS = getenv("BINDER_ADDRESS");
      BINDER_PORT = getenv("BINDER_PORT");

      binderSockFd = call_sock(BINDER_ADDRESS, BINDER_PORT);
    }
  public:
    static ClientProcess* getInstance() {
      if(singleton == 0) {
        singleton = new ClientProcess();
      }
      return singleton;
    }

    int getBinderSockFd(){
      return binderSockFd;
    }

    int read_message(int sockfd) {
      int resp;
      int* head = read_head(sockfd);
      int len = head[0];
      int type = head[1];

      switch(type) {
        case RPC_LOC_SUCCESS:
          resp = read_loc_success(sockfd); //could make use of ClientResp here
          break;
        case RPC_LOC_FAILURE:
          resp = read_loc_failure(sockfd);
          break;
        case RPC_EXECUTE_SUCCESS:
          resp = read_execute_success(sockfd, len);
          break;
        case RPC_EXECUTE_FAILURE:
          resp = read_execute_failure(sockfd);
          break;
        default:
          resp = INVALID_MESSAGE;
      }

      //TODO -- based on the response received, act.
      return 0;
    }

    int read_loc_success(int sockfd) {
      char hostname[sizeof(char)*128];
      unsigned short port;
      int nbytes;

      nbytes = recv(sockfd, hostname, (sizeof(char)*128), 0);

      nbytes = recv(sockfd, &port, sizeof(unsigned short), 0);

      cout << "LOC_SUCCESS :: " << "Server located has hostname: " << hostname << " and port: " << port << endl;

      // client stores this for every call and cleans it when execute message has been sent
      locationForCall = new ServerPortCombo(hostname, port);

      return 0;
    }

    int read_loc_failure(int sockfd) {
      int nbytes;
      int reasonCode;

      nbytes = recv(sockfd, &reasonCode, sizeof(int), 0);

      printf("LOC_FAILURE :: The reasonCode is: %d\n", reasonCode);
      return 0;
    }

    int read_execute_success(int sockfd, int len) {

    }

    int read_execute_failure(int sockfd) {
      int nbytes;
      int reasonCode;

      nbytes = recv(sockfd, &reasonCode, sizeof(int), 0);

      printf("EXECUTE_FAILURE :: The reasonCode is: %d\n", reasonCode);
      return 0;
    }

    // blocking call - wait on the binder to respond and then act accordingly
    int locationRequest(char* name, int* argTypes, int sizeOfArgTypes){
      int resp = send_loc_request(binderSockFd, name, argTypes, sizeOfArgTypes);

      // TODO The only bad thing that can happen here is that binder hangs up before data is sent

      return 0;
    }

    int execute(char * name, int * argTypes, void ** args) {
      int sizeOfArgs = 0;
      char hostname[128];
      unsigned short port;

      if (locationForCall != NULL) {
        strcpy(hostname, locationForCall->name.c_str());
        port = locationForCall->port;

        cout << "execute :: " << "Sending execute to: " << hostname << ":" << port << endl;
        int resp = send_execute(binderSockFd, hostname, port, argTypes, N_ELEMENTS(argTypes), args, sizeOfArgs);

        //free the server/port object
        delete locationForCall;
      }

    }

    int terminate() {
      int res = send_terminate(binderSockFd);
      return res;
    }

};

ClientProcess* ClientProcess::singleton = NULL;

// blocking call to binder and then server
int rpcCall(char* name, int* argTypes, void** args) {
  // locate server for me
  int binderSockFd = ClientProcess::getInstance()->getBinderSockFd();

  int resp = ClientProcess::getInstance()->locationRequest(name, argTypes, N_ELEMENTS(argTypes)); // fire the message to binder

  resp = ClientProcess::getInstance()->read_message(binderSockFd); // read either loc_success / failure

  //TODO if the resp was that the location lookup was unsuccessful, then return now

  //resp = ClientProcess::getInstance()->execute(char * name, int * argTypes, void ** args); // fire the message to server that was located

  //resp = ClientProcess::getInstance()->read_message(binderSockFd);

  //TODO if the execution was successful then return 0;
  return 0;
}

int rpcTerminate() {
  //send the terminate message to the binder
  int res = ClientProcess::getInstance()->terminate();
  return res;
}

int main() {
  int binderSockFd = ClientProcess::getInstance()->getBinderSockFd();

  char name[64] = "derp";
  int argTypes1[5];
  argTypes1[0] = (1 << ARG_OUTPUT) | (ARG_INT << 16);
  argTypes1[1] = (1 << ARG_INPUT)  | (1 << ARG_OUTPUT) | (ARG_INT << 16) | 23;
  argTypes1[2] = (1 << ARG_INPUT)  | (1 << ARG_OUTPUT) | (ARG_INT << 16);
  argTypes1[3] = (1 << ARG_INPUT)  | (1 << ARG_OUTPUT) | (ARG_LONG << 16) | 23;
  argTypes1[4] = 0;

  int resp = ClientProcess::getInstance()->locationRequest(name, argTypes1, N_ELEMENTS(argTypes1)); // fire the message to binder

  resp = ClientProcess::getInstance()->read_message(binderSockFd); // read either loc_success / failure

  //printf("The size of func: %d\n and size of argTypes: %d\n", N_ELEMENTS(func), N_ELEMENTS(argTypes));
  //rpcCall()

  //close(ClientProcess::getInstance()->getBinderSockFd()); // TODO I don't think we ever close conn to binder -- perhaps in binder
  return 0;
}

<commit_msg>small changes to make things work<commit_after>/*
 * client_proc.cpp
 *
 * This is the client process
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <iostream>
#include <string>
#include <vector>

#include "rpc.h"
#include "sck_stream.h"
#include "message_protocol.h"
#include "utility.h";
#include "response_codes.h"

using namespace std;

class ClientProcess {
  private:
    static ClientProcess* singleton;
    int binderSockFd;
    char* BINDER_ADDRESS;
    char* BINDER_PORT;

  protected:
    ClientProcess() { // called only once in the ctr
      BINDER_ADDRESS = getenv("BINDER_ADDRESS");
      BINDER_PORT = getenv("BINDER_PORT");

      binderSockFd = call_sock(BINDER_ADDRESS, BINDER_PORT);
      locationForCall = NULL;
    }
  public:
    ServerPortCombo* locationForCall;

    static ClientProcess* getInstance() {
      if(singleton == 0) {
        singleton = new ClientProcess();
      }
      return singleton;
    }

    int getBinderSockFd(){
      return binderSockFd;
    }

    int read_message(int sockfd) {
      int resp;
      int* head = read_head(sockfd);
      int len = head[0];
      int type = head[1];

      switch(type) {
        case RPC_LOC_SUCCESS:
          resp = read_loc_success(sockfd); //could make use of ClientResp here
          break;
        case RPC_LOC_FAILURE:
          resp = read_loc_failure(sockfd);
          break;
        case RPC_EXECUTE_SUCCESS:
          resp = read_execute_success(sockfd, len);
          break;
        case RPC_EXECUTE_FAILURE:
          resp = read_execute_failure(sockfd);
          break;
        default:
          resp = INVALID_MESSAGE;
      }

      //TODO -- based on the response received, act.
      return 0;
    }

    int read_loc_success(int sockfd) {
      char hostname[sizeof(char)*128];
      unsigned short port;
      int nbytes;

      nbytes = recv(sockfd, hostname, (sizeof(char)*128), 0);

      nbytes = recv(sockfd, &port, sizeof(unsigned short), 0);

      cout << "LOC_SUCCESS :: " << "Server located has hostname: " << hostname << " and port: " << port << endl;

      // client stores this for every call and cleans it when execute message has been sent
      locationForCall = new ServerPortCombo(hostname, port);

      return 0;
    }

    int read_loc_failure(int sockfd) {
      int nbytes;
      int reasonCode;

      nbytes = recv(sockfd, &reasonCode, sizeof(int), 0);

      printf("LOC_FAILURE :: The reasonCode is: %d\n", reasonCode);
      return 0;
    }

    int read_execute_success(int sockfd, int len) {

    }

    int read_execute_failure(int sockfd) {
      int nbytes;
      int reasonCode;

      nbytes = recv(sockfd, &reasonCode, sizeof(int), 0);

      printf("EXECUTE_FAILURE :: The reasonCode is: %d\n", reasonCode);
      return 0;
    }

    // blocking call - wait on the binder to respond and then act accordingly
    int locationRequest(char* name, int* argTypes, int sizeOfArgTypes){
      int resp = send_loc_request(binderSockFd, name, argTypes, sizeOfArgTypes);

      // TODO The only bad thing that can happen here is that binder hangs up before data is sent

      return 0;
    }

    int execute(char * name, int * argTypes, void ** args) {
      int sizeOfArgs = 0;
      char hostname[128];
      unsigned short port;

      if (locationForCall != NULL) {
        strcpy(hostname, locationForCall->name.c_str());
        port = locationForCall->port;

        cout << "execute :: " << "Sending execute to: " << hostname << ":" << port << endl;
        // this method is actually sent to the server not the binder
        int resp = send_execute(binderSockFd, hostname, port, argTypes, N_ELEMENTS(argTypes), args, sizeOfArgs);

        //free the server/port object
        delete locationForCall;
      }

    }

    int terminate() {
      int res = send_terminate(binderSockFd);
      return res;
    }

};

ClientProcess* ClientProcess::singleton = NULL;

// blocking call to binder and then server
int rpcCall(char* name, int* argTypes, void** args) {
  // locate server for me
  int binderSockFd = ClientProcess::getInstance()->getBinderSockFd();

  int resp = ClientProcess::getInstance()->locationRequest(name, argTypes, N_ELEMENTS(argTypes)); // fire the message to binder

  resp = ClientProcess::getInstance()->read_message(binderSockFd); // read either loc_success / failure

  //TODO if the resp was that the location lookup was unsuccessful, then return now

  //resp = ClientProcess::getInstance()->execute(char * name, int * argTypes, void ** args); // fire the message to server that was located

  //resp = ClientProcess::getInstance()->read_message(binderSockFd);

  //TODO if the execution was successful then return 0;
  return 0;
}

int rpcTerminate() {
  //send the terminate message to the binder
  int res = ClientProcess::getInstance()->terminate();
  return res;
}

int main() {
  int binderSockFd = ClientProcess::getInstance()->getBinderSockFd();

  char name[64] = "derp";
  int argTypes1[5];
  argTypes1[0] = (1 << ARG_OUTPUT) | (ARG_INT << 16);
  argTypes1[1] = (1 << ARG_INPUT)  | (1 << ARG_OUTPUT) | (ARG_INT << 16) | 23;
  argTypes1[2] = (1 << ARG_INPUT)  | (1 << ARG_OUTPUT) | (ARG_INT << 16);
  argTypes1[3] = (1 << ARG_INPUT)  | (1 << ARG_OUTPUT) | (ARG_LONG << 16) | 23;
  argTypes1[4] = 0;

  int resp = ClientProcess::getInstance()->locationRequest(name, argTypes1, N_ELEMENTS(argTypes1)); // fire the message to binder

  resp = ClientProcess::getInstance()->read_message(binderSockFd); // read either loc_success / failure

  //printf("The size of func: %d\n and size of argTypes: %d\n", N_ELEMENTS(func), N_ELEMENTS(argTypes));
  //rpcCall()

  //close(ClientProcess::getInstance()->getBinderSockFd()); // TODO I don't think we ever close conn to binder -- perhaps in binder
  return 0;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <string>
#include <map>
#include <set>

// Loriano: let's try Armadillo quick code
#include <armadillo>
#include <cassert>

#include <getopt.h>
#include <unistd.h>
#include <alloca.h>

#include <pcafitter.hpp>
#include <pcaffunctype.hpp>

// lstorchi: basi code to fit tracks, using the PCA constants generated
//           by the related generatepca

bool build_and_compare (arma::mat & paramslt, arma::mat & coordslt,
     arma::mat & cmtx, arma::rowvec & q, bool verbose,
     pca::pcafitter & fitter)
{
  double * cotethacmp, * z0cmp;
  cotethacmp = new double [(int)coordslt.n_rows];
  z0cmp = new double [(int)coordslt.n_rows];

  double ** ptrs;
  ptrs = new double* [fitter.get_paramdim()];
  ptrs[SPLIT_COTTETHAIDX] = cotethacmp;
  ptrs[SPLIT_Z0IDX] = z0cmp;

  if (!fitter.compute_parameters (cmtx, q, coordslt, ptrs,
        fitter.get_paramdim()))
  {
    std::cerr << fitter.get_errmsg() << std::endl;
    return false;
  }

  delete [] ptrs;

  std::ostringstream fname;
  fname << "results.txt";

  std::ofstream myfile(fname.str().c_str());
  myfile << "eta_orig eta_cmpt diff z0_orig z0_cmpt diff" << std::endl;

  arma::running_stat<double> pc[fitter.get_paramdim()];
  for (int i=0; i<(int)coordslt.n_rows; ++i)
  {
    double tantetha = (1.0e0 / cotethacmp[i]) ;
    double etacmps = -1.0e0 * log (tantetha);
    tantetha = (1.0e0 / paramslt(i, SPLIT_COTTETHAIDX));
    double etaorig = -1.0e0 * log (tantetha);

    pc[SPLIT_COTTETHAIDX](fabs(etacmps - etaorig)/
        (fabs(etacmps + etaorig)/2.0));
    pc[SPLIT_Z0IDX](fabs(z0cmp[i] - paramslt(i, SPLIT_Z0IDX))/
        (fabs(z0cmp[i] + paramslt(i, SPLIT_Z0IDX))/2.0));

    myfile <<
      etaorig << " " << etacmps << " " <<
      (etacmps - etaorig) << " " <<
      paramslt(i, SPLIT_Z0IDX) << " " << z0cmp[i] << " " <<
      (z0cmp[i] - paramslt(i, SPLIT_Z0IDX)) << std::endl;

    if (verbose)
    {
      std::cout << "For track : " << i+1 << std::endl;
      std::cout << " eta          cmpt " << etacmps << std::endl;
      std::cout << " eta          calc " << etaorig << std::endl;
      std::cout << " z0           cmpt " << z0cmp[i] << std::endl;
      std::cout << " z0           calc " << paramslt(i, SPLIT_Z0IDX) << std::endl;
    }
  }

  myfile.close();

  for (int i=0; i<fitter.get_paramdim(); ++i)
     std::cout << "For " << fitter.paramidx_to_string(i) << " error " <<
       100.0*pc[i].mean() << " " << 100.0*pc[i].stddev() << std::endl;

  delete [] cotethacmp;
  delete [] z0cmp;

  return true;
}

void usage (char * name)
{
  std::cerr << "usage: " << name << " [options] coordinatesfile " << std::endl;
  std::cerr << std::endl;
  std::cerr << " -h, --help               : display this help and exit" << std::endl;
  std::cerr << " -V, --verbose            : verbose option on" << std::endl;
  std::cerr << " -v, --version            : print version and exit" << std::endl;
  std::cerr << " -c, --cmtx=[fillename]   : CMTX filename [default is c.<selectedsubsecid>.bin]" << std::endl;
  std::cerr << " -q, --qvct=[fillename]   : QVCT filename [default is q.<selectedsubsecid>.bin]" << std::endl;
  std::cerr << " -j, --jump-tracks        : perform the fittin only for odd tracks" << std::endl;

  exit(1);
}

int main (int argc, char ** argv)
{
  pca::pcafitter fitter;

  std::string qfname = "q.bin";
  std::string cfname = "c.bin";
  std::string subsec = "";
  std::string sublad = "";
  bool verbose = false;
  bool useonlyodd = false;

  while (1)
  {
    int c, option_index;
    static struct option long_options[] = {
      {"help", 0, NULL, 'h'},
      {"cmtx", 1, NULL, 'c'},
      {"qvct", 1, NULL, 'q'},
      {"verbose", 0, NULL, 'V'},
      {"version", 0, NULL, 'v'},
      {"jump-tracks", 0, NULL, 'j'},
      {0, 0, 0, 0}
    };

    c = getopt_long (argc, argv, "hVc:q:s:j", long_options, &option_index);

    if (c == -1)
      break;

    switch (c)
    {
      case 'j':
        useonlyodd = true;
        break;
      case 'V':
        verbose = true;
        break;
      case 'v':
        std::cout << "Version: " << pca::pcafitter::get_version_string() << std::endl;
        exit(1);
        break;
      case 'h':
        usage (argv[0]);
        break;
      case'c':
        cfname = optarg;
        break;
      case 'q':
        qfname = optarg;
        break;
      default:
        usage (argv[0]);
        break;
    }
  }

  // R-z
  fitter.set_coordim (2*6);

  fitter.set_paramdim(2);
  if (!fitter.set_paramidx(SPLIT_COTTETHAIDX, "cot(tetha/2)"))
  {
    std::cerr << fitter.get_errmsg() << std::endl;
    return EXIT_FAILURE;
  }
  if (!fitter.set_paramidx(SPLIT_Z0IDX, "z0"))
  {
    std::cerr << fitter.get_errmsg() << std::endl;
    return EXIT_FAILURE;
  }

  if (optind >= argc)
    usage (argv[0]);

  char * filename = (char *) alloca (strlen(argv[optind]) + 1);
  strcpy (filename, argv[optind]);

  // leggere file coordinate tracce e file costanti PCA
  // N righe di 9 double sono le coordinate
  // matrice C e vettore q sono le costanti

  arma::mat cmtx;
  arma::rowvec q;

  // leggere file coordinate tracce simulate plus parametri
  if (!pca::file_exists(filename))
  {
    std::cerr << "Inout file does not exist" << std::endl;
    return EXIT_FAILURE;
  }

  std::cout << "Reading data from " << filename << " file " << std::endl;
  int num_of_line = pca::numofline(filename);
  std::cout << "file has " << num_of_line << " line " << std::endl;
  int num_of_ent_read = (num_of_line-1)/ENTDIM;

  int num_of_ent = num_of_ent_read;

  if (useonlyodd)
  {
    if (num_of_ent_read % 2)
      num_of_ent = (num_of_ent_read+1)/2;
    else
      num_of_ent = num_of_ent_read/2;
  }

  std::cout << "file has " << num_of_ent << " entries " << std::endl;

  arma::mat coord, param;
  coord.set_size(num_of_ent,fitter.get_coordim());
  param.set_size(num_of_ent,fitter.get_paramdim());

  pca::reading_from_file_split (filename,
     param, coord, num_of_ent, false, useonlyodd,
     true, false);

  pca::read_armmat(cfname.c_str(), cmtx);
  pca::read_armvct(qfname.c_str(), q);

  if (!build_and_compare (param, coord, cmtx, q, verbose,
          fitter))
    return EXIT_FAILURE;

  return EXIT_SUCCESS;
}
<commit_msg>first fit split implementation (train way back, so check it)<commit_after>#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <string>
#include <map>
#include <set>

// Loriano: let's try Armadillo quick code
#include <armadillo>
#include <cassert>

#include <getopt.h>
#include <unistd.h>
#include <alloca.h>

#include <pcafitter.hpp>
#include <pcaffunctype.hpp>

// lstorchi: basi code to fit tracks, using the PCA constants generated
//           by the related generatepca

bool build_and_compare (arma::mat & paramslt, arma::mat & coordslt,
     arma::mat & cmtx, arma::rowvec & q, bool verbose,
     pca::pcafitter & fitter, bool rzplane, bool rphiplane)
{
  double ** ptrs;
  ptrs = new double* [fitter.get_paramdim()];

  double * cotethacmp, * z0cmp, * ptcmp, * phicmp;

  if (rzplane)
  {
    cotethacmp = new double [(int)coordslt.n_rows];
    z0cmp = new double [(int)coordslt.n_rows];

    ptrs[SPLIT_COTTETHAIDX] = cotethacmp;
    ptrs[SPLIT_Z0IDX] = z0cmp;
  }
  else if (rphiplane)
  {
    ptcmp = new double [(int)coordslt.n_rows];
    phicmp = new double [(int)coordslt.n_rows];

    ptrs[SPLIT_PTIDX] = ptcmp;
    ptrs[SPLIT_PHIIDX] = phicmp;
  }

  if (!fitter.compute_parameters (cmtx, q, coordslt, ptrs,
        fitter.get_paramdim()))
  {
    std::cerr << fitter.get_errmsg() << std::endl;
    return false;
  }

  delete [] ptrs;

  std::ostringstream fname;
  fname << "results.txt";

  arma::running_stat<double> pc[fitter.get_paramdim()];
  std::ofstream myfile(fname.str().c_str());

  if (rzplane)
  {
    myfile << "eta_orig eta_cmpt diff z0_orig z0_cmpt diff" << std::endl;

    for (int i=0; i<(int)coordslt.n_rows; ++i)
    {
      double tantetha = (1.0e0 / cotethacmp[i]) ;
      double etacmps = -1.0e0 * log (tantetha);
      tantetha = (1.0e0 / paramslt(i, SPLIT_COTTETHAIDX));
      double etaorig = -1.0e0 * log (tantetha);

      pc[SPLIT_COTTETHAIDX](fabs(etacmps - etaorig)/
          (fabs(etacmps + etaorig)/2.0));
      pc[SPLIT_Z0IDX](fabs(z0cmp[i] - paramslt(i, SPLIT_Z0IDX))/
          (fabs(z0cmp[i] + paramslt(i, SPLIT_Z0IDX))/2.0));

      myfile <<
        etaorig << " " << etacmps << " " <<
        (etacmps - etaorig) << " " <<
        paramslt(i, SPLIT_Z0IDX) << " " << z0cmp[i] << " " <<
        (z0cmp[i] - paramslt(i, SPLIT_Z0IDX)) << std::endl;

      if (verbose)
      {
        std::cout << "For track : " << i+1 << std::endl;
        std::cout << " eta          cmpt " << etacmps << std::endl;
        std::cout << " eta          calc " << etaorig << std::endl;
        std::cout << " z0           cmpt " << z0cmp[i] << std::endl;
        std::cout << " z0           calc " << paramslt(i, SPLIT_Z0IDX) << std::endl;
      }
    }
  }
  else if (rphiplane)
  {
    std::ofstream myfile(fname.str().c_str());
    myfile << "pt_orig pt_cmpt diff phi_orig phi_cmpt diff" << std::endl;

    arma::running_stat<double> pc[fitter.get_paramdim()];
    for (int i=0; i<(int)coordslt.n_rows; ++i)
    {
      pc[SPLIT_PHIIDX](fabs(phicmp[i] - paramslt(i, SPLIT_PHIIDX))/
          (fabs(phicmp[i] + paramslt(i, SPLIT_PHIIDX))/2.0));

      pc[SPLIT_PTIDX](fabs(1.0e0/ptcmp[i] - 1.0e0/paramslt(i, SPLIT_PTIDX))/
          (fabs(1.0e0/ptcmp[i] + 1.0e0/paramslt(i, SPLIT_PTIDX))/2.0));

      myfile <<
        1.0e0/paramslt(i, SPLIT_PTIDX) << " " << 1.0e0/ptcmp[i] << " " <<
        (1.0e0/ptcmp[i] - 1.0e0/paramslt(i, SPLIT_PTIDX)) <<  " " <<
        paramslt(i, SPLIT_PHIIDX) << " " << phicmp[i] << " " <<
        (phicmp[i] - paramslt(i, SPLIT_PHIIDX)) << std::endl;

      if (verbose)
      {
        std::cout << "For track : " << i+1 << std::endl;
        std::cout << " pt           cmpt " << 1.0e0/ptcmp[i] << std::endl;
        std::cout << " pt           calc " << 1.0e0/paramslt(i, SPLIT_PTIDX)  << std::endl;
        std::cout << " phi          cmpt " << phicmp[i] << std::endl;
        std::cout << " phi          calc " << paramslt(i, SPLIT_PHIIDX) << std::endl;
      }
    }
  }

  myfile.close();

  for (int i=0; i<fitter.get_paramdim(); ++i)
     std::cout << "For " << fitter.paramidx_to_string(i) << " error " <<
       100.0*pc[i].mean() << " " << 100.0*pc[i].stddev() << std::endl;

  if (rzplane)
  {
    delete [] cotethacmp;
    delete [] z0cmp;
  }
  else if (rphiplane)
  {
    delete [] ptcmp;
    delete [] phicmp;
  }

  return true;
}

void usage (char * name)
{
  std::cerr << "usage: " << name << " [options] coordinatesfile " << std::endl;
  std::cerr << std::endl;
  std::cerr << " -h, --help               : display this help and exit" << std::endl;
  std::cerr << " -V, --verbose            : verbose option on" << std::endl;
  std::cerr << " -v, --version            : print version and exit" << std::endl;
  std::cerr << " -c, --cmtx=[fillename]   : CMTX filename [default is c.<selectedsubsecid>.bin]" << std::endl;
  std::cerr << " -q, --qvct=[fillename]   : QVCT filename [default is q.<selectedsubsecid>.bin]" << std::endl;
  std::cerr << " -j, --jump-tracks        : perform the fittin only for odd tracks" << std::endl;
  std::cerr << " -z, --rz-plane           : use rz plane view" << std::endl;
  std::cerr << " -r, --rphi-plane         : use r-phi plane view" << std::endl;

  exit(1);
}

int main (int argc, char ** argv)
{
  pca::pcafitter fitter;

  std::string qfname = "q.bin";
  std::string cfname = "c.bin";
  std::string subsec = "";
  std::string sublad = "";
  bool verbose = false;
  bool useonlyodd = false;
  bool rzplane = false;
  bool rphiplane = false;

  while (1)
  {
    int c, option_index;
    static struct option long_options[] = {
      {"help", 0, NULL, 'h'},
      {"cmtx", 1, NULL, 'c'},
      {"qvct", 1, NULL, 'q'},
      {"verbose", 0, NULL, 'V'},
      {"version", 0, NULL, 'v'},
      {"jump-tracks", 0, NULL, 'j'},
      {"rz-plane", 0, NULL, 'z'},
      {"rphi-plane", 0, NULL, 'r'},
      {0, 0, 0, 0}
    };

    c = getopt_long (argc, argv, "zrhVc:q:s:j", long_options, &option_index);

    if (c == -1)
      break;

    switch (c)
    {
      case 'z':
        rzplane = true;
        break;
      case 'r':
        rphiplane = true;
        break;
      case 'j':
        useonlyodd = true;
        break;
      case 'V':
        verbose = true;
        break;
      case 'v':
        std::cout << "Version: " << pca::pcafitter::get_version_string() << std::endl;
        exit(1);
        break;
      case 'h':
        usage (argv[0]);
        break;
      case'c':
        cfname = optarg;
        break;
      case 'q':
        qfname = optarg;
        break;
      default:
        usage (argv[0]);
        break;
    }
  }

  if (optind >= argc)
    usage (argv[0]);

  if ((rzplane && rphiplane) ||
      (!rzplane && !rphiplane))
  {
    std::cerr << "r-phi or r-z plane ?" << std::endl;
    usage (argv[0]);
  }

  // R-z
  fitter.set_coordim (2*6);

  fitter.set_paramdim(2);
  if (rzplane)
  {
    if (!fitter.set_paramidx(SPLIT_COTTETHAIDX, "cot(tetha/2)"))
    {
      std::cerr << fitter.get_errmsg() << std::endl;
      return EXIT_FAILURE;
    }
    if (!fitter.set_paramidx(SPLIT_Z0IDX, "z0"))
    {
      std::cerr << fitter.get_errmsg() << std::endl;
      return EXIT_FAILURE;
    }
  }
  else if (rphiplane)
  {
    if (!fitter.set_paramidx(SPLIT_PHIIDX, "phi"))
    {
      std::cerr << fitter.get_errmsg() << std::endl;
      return EXIT_FAILURE;
    }
    if (!fitter.set_paramidx(SPLIT_PTIDX, "1/pt"))
    {
      std::cerr << fitter.get_errmsg() << std::endl;
      return EXIT_FAILURE;
    }
  }

  char * filename = (char *) alloca (strlen(argv[optind]) + 1);
  strcpy (filename, argv[optind]);

  // leggere file coordinate tracce e file costanti PCA
  // N righe di 9 double sono le coordinate
  // matrice C e vettore q sono le costanti

  arma::mat cmtx;
  arma::rowvec q;

  // leggere file coordinate tracce simulate plus parametri
  if (!pca::file_exists(filename))
  {
    std::cerr << "Inout file does not exist" << std::endl;
    return EXIT_FAILURE;
  }

  std::cout << "Reading data from " << filename << " file " << std::endl;
  int num_of_line = pca::numofline(filename);
  std::cout << "file has " << num_of_line << " line " << std::endl;
  int num_of_ent_read = (num_of_line-1)/ENTDIM;

  int num_of_ent = num_of_ent_read;

  if (useonlyodd)
  {
    if (num_of_ent_read % 2)
      num_of_ent = (num_of_ent_read+1)/2;
    else
      num_of_ent = num_of_ent_read/2;
  }

  std::cout << "file has " << num_of_ent << " entries " << std::endl;

  arma::mat coord, param;
  coord.set_size(num_of_ent,fitter.get_coordim());
  param.set_size(num_of_ent,fitter.get_paramdim());

  pca::reading_from_file_split (filename,
     param, coord, num_of_ent, false, useonlyodd,
     rzplane, rphiplane);

  pca::read_armmat(cfname.c_str(), cmtx);
  pca::read_armvct(qfname.c_str(), q);

  if (!build_and_compare (param, coord, cmtx, q, verbose,
          fitter, rzplane, rphiplane))
    return EXIT_FAILURE;

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>//
// Name:	ModelDlg.cpp
//
// Copyright (c) 2001-2002 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
	#pragma implementation "ModelDlg.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef _MSC_VER
#pragma warning( disable : 4786 )
#endif

#include "ModelDlg.h"
#include "vtdata/Content.h"
#include "Frame.h"

// WDR: class implementations

//----------------------------------------------------------------------------
// ModelDlg
//----------------------------------------------------------------------------

// WDR: event table for ModelDlg

BEGIN_EVENT_TABLE(ModelDlg,AutoPanel)
	EVT_TEXT( ID_FILENAME, ModelDlg::OnTextFilename )
	EVT_TEXT_ENTER( ID_DISTANCE, ModelDlg::OnTextVisible )
	EVT_TEXT_ENTER( ID_SCALE, ModelDlg::OnTextScale )
END_EVENT_TABLE()

ModelDlg::ModelDlg( wxWindow *parent, wxWindowID id,
	const wxPoint &position, const wxSize& size, long style ) :
	AutoPanel( parent, id, position, size, style )
{
	m_bUpdating = false;
	m_pCurrentModel = NULL;
	ModelDialogFunc( this, TRUE );
}

// WDR: handler implementations for ModelDlg

void ModelDlg::OnTextScale( wxCommandEvent &event )
{
	UpdateFromControls();

	if (!m_pCurrentModel)
		return;

	// change in Scale should be passed to the 3d scene graph
	GetMainFrame()->UpdateScale(m_pCurrentModel);
	GetMainFrame()->ZoomToCurrentModel();
}

void ModelDlg::OnTextVisible( wxCommandEvent &event )
{
	if (m_bUpdating)
		return;

	UpdateFromControls();

	// change in LOD visibility distance should be passed to the 3d scene graph
	GetMainFrame()->UpdateCurrentModelLOD();
}

void ModelDlg::OnTextFilename( wxCommandEvent &event )
{
	UpdateFromControls();
}

void ModelDlg::SetCurrentModel(vtModel *model)
{
	if (model)
	{
		m_strFilename = model->m_filename;
		m_fDistance = model->m_distance;
		m_fScale = model->m_scale;
	}
	else
	{
		m_strFilename = "";
		m_fDistance = 0.0f;
		m_fScale = 1.0f;
		m_strStatus = "";
	}
	m_pCurrentModel = model;
	m_bUpdating = true;
	TransferDataToWindow();
	m_bUpdating = false;
}

void ModelDlg::SetModelStatus(const char *string)
{
	m_strStatus = string;
	TransferDataToWindow();
}

void ModelDlg::UpdateFromControls()
{
	if (m_bUpdating)
		return;

	TransferDataFromWindow();
	if (m_pCurrentModel)
	{
		m_pCurrentModel->m_filename = m_strFilename.mb_str();
		m_pCurrentModel->m_distance = m_fDistance;
		m_pCurrentModel->m_scale = m_fScale;
	}
}

void ModelDlg::OnInitDialog(wxInitDialogEvent& event)
{
	AddValidator(ID_FILENAME, &m_strFilename);
	AddNumValidator(ID_DISTANCE, &m_fDistance);
	AddNumValidator(ID_SCALE, &m_fScale);
	AddValidator(ID_STATUS, &m_strStatus);
}

<commit_msg>fixed display of model scale<commit_after>//
// Name:	ModelDlg.cpp
//
// Copyright (c) 2001-2002 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
	#pragma implementation "ModelDlg.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef _MSC_VER
#pragma warning( disable : 4786 )
#endif

#include "ModelDlg.h"
#include "vtdata/Content.h"
#include "Frame.h"

// WDR: class implementations

//----------------------------------------------------------------------------
// ModelDlg
//----------------------------------------------------------------------------

// WDR: event table for ModelDlg

BEGIN_EVENT_TABLE(ModelDlg,AutoPanel)
	EVT_TEXT( ID_FILENAME, ModelDlg::OnTextFilename )
	EVT_TEXT_ENTER( ID_DISTANCE, ModelDlg::OnTextVisible )
	EVT_TEXT_ENTER( ID_SCALE, ModelDlg::OnTextScale )
END_EVENT_TABLE()

ModelDlg::ModelDlg( wxWindow *parent, wxWindowID id,
	const wxPoint &position, const wxSize& size, long style ) :
	AutoPanel( parent, id, position, size, style )
{
	m_bUpdating = false;
	m_pCurrentModel = NULL;
	ModelDialogFunc( this, TRUE );
}

// WDR: handler implementations for ModelDlg

void ModelDlg::OnTextScale( wxCommandEvent &event )
{
	UpdateFromControls();

	if (!m_pCurrentModel)
		return;

	// change in Scale should be passed to the 3d scene graph
	GetMainFrame()->UpdateScale(m_pCurrentModel);
	GetMainFrame()->ZoomToCurrentModel();
}

void ModelDlg::OnTextVisible( wxCommandEvent &event )
{
	if (m_bUpdating)
		return;

	UpdateFromControls();

	// change in LOD visibility distance should be passed to the 3d scene graph
	GetMainFrame()->UpdateCurrentModelLOD();
}

void ModelDlg::OnTextFilename( wxCommandEvent &event )
{
	UpdateFromControls();
}

void ModelDlg::SetCurrentModel(vtModel *model)
{
	if (model)
	{
		m_strFilename = model->m_filename;
		m_fDistance = model->m_distance;
		m_fScale = model->m_scale;
	}
	else
	{
		m_strFilename = "";
		m_fDistance = 0.0f;
		m_fScale = 1.0f;
		m_strStatus = "";
	}
	m_pCurrentModel = model;
	m_bUpdating = true;
	TransferDataToWindow();
	m_bUpdating = false;
}

void ModelDlg::SetModelStatus(const char *string)
{
	m_strStatus = string;
	TransferDataToWindow();
}

void ModelDlg::UpdateFromControls()
{
	if (m_bUpdating)
		return;

	TransferDataFromWindow();
	if (m_pCurrentModel)
	{
		m_pCurrentModel->m_filename = m_strFilename.mb_str();
		m_pCurrentModel->m_distance = m_fDistance;
		m_pCurrentModel->m_scale = m_fScale;
	}
}

void ModelDlg::OnInitDialog(wxInitDialogEvent& event)
{
	AddValidator(ID_FILENAME, &m_strFilename);
	AddNumValidator(ID_DISTANCE, &m_fDistance);
	AddNumValidator(ID_SCALE, &m_fScale, 5);
	AddValidator(ID_STATUS, &m_strStatus);
}

<|endoftext|>


<commit_before>//
// Name:        NodeDlg.cpp
//
// Copyright (c) 2002 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
    #pragma implementation "NodeDlg.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
    #pragma hdrstop
#endif

#include "NodeDlg.h"
#include "RoadLayer.h"
#include "Frame.h"
#include "BuilderView.h"

#define MULTIPLE    5000

// WDR: class implementations

//----------------------------------------------------------------------------
// NodeDlg
//----------------------------------------------------------------------------

// WDR: event table for NodeDlg

BEGIN_EVENT_TABLE(NodeDlg,AutoDialog)
    EVT_BUTTON( wxID_OK, NodeDlg::OnOK )
    EVT_PAINT(NodeDlg::OnPaint)
    EVT_LISTBOX( ID_INTTYPE, NodeDlg::OnIntType )
    EVT_LISTBOX( ID_ROADNUM, NodeDlg::OnRoadNum )
    EVT_LISTBOX( ID_BEHAVIOR, NodeDlg::OnBehavior )
END_EVENT_TABLE()

NodeDlg::NodeDlg( wxWindow *parent, wxWindowID id, const wxString &title,
    const wxPoint &position, const wxSize& size, long style ) :
    AutoDialog( parent, id, title, position, size, style )
{
    NodePropDialogFunc( this, TRUE );
}

void NodeDlg::SetNode(NodeEdit *pSingleNode, vtRoadLayer *pLayer)
{
    m_pNode = pSingleNode;
    m_pLayer = pLayer;
}

// WDR: handler implementations for NodeDlg

void NodeDlg::OnBehavior( wxCommandEvent &event )
{
	int sel = GetRoadNum()->GetSelection();
	//select new behavior and redraw it on the dialog.
	int itype = GetBehavior()->GetSelection();
	m_pNode->SetIntersectType(sel, (IntersectionType)itype );

	// this may have changed the VIT, so check
	m_pNode->DetermineVisualFromRoads();
    GetIntType()->SetSelection(m_pNode->GetVisual());

	Refresh();
}

void NodeDlg::OnRoadNum( wxCommandEvent &event )
{
	int sel = GetRoadNum()->GetSelection();
	//update what the behavior shows to match that of the road
	GetBehavior()->SetSelection(m_pNode->GetIntersectType(sel));
}

void NodeDlg::OnIntType( wxCommandEvent &event )
{
	//new node behavior
	VisualIntersectionType vitype;
	int sel = GetIntType()->GetSelection();
	if (sel == 0 || sel == 6)	// unknown or multiple not allowed
		return;

	vitype = (VisualIntersectionType) sel;

	if (m_pNode)
		ApplyVisualToNode(m_pNode, vitype);
	else
	{
        for (NodeEdit *n = m_pLayer->GetFirstNode(); n; n=n->GetNext())
        {
            if (!n->IsSelected())
                continue;
			ApplyVisualToNode(n, vitype);
		}
	}
	Refresh();
}

void NodeDlg::ApplyVisualToNode(NodeEdit *pNode, VisualIntersectionType vitype)
{
	int i;

	pNode->SetVisual(vitype);

	//overwrite all behaviors at the roads to match new assigned node behavior.
	switch (vitype)
	{
	case VIT_NONE:
		//make all intersections uncontrolled
		for (i = 0; i < m_pNode->m_iRoads; i++) {
			pNode->SetIntersectType(i, IT_NONE);
		}
		GetBehavior()->SetSelection(IT_NONE);
		break;
	case VIT_ALLSTOPS:
		//make all intersections stop signs
		for (i = 0; i < m_pNode->m_iRoads; i++) {
			pNode->SetIntersectType(i, IT_STOPSIGN);
		}
		GetBehavior()->SetSelection(IT_STOPSIGN);
		break;
	case VIT_ALLLIGHTS:
		//make all intersections lights
		for (i = 0; i < m_pNode->m_iRoads; i++) {
			pNode->SetIntersectType(i, IT_LIGHT);
		}
		GetBehavior()->SetSelection(IT_LIGHT);
		pNode->AdjustForLights();
		break;
	}
}

void NodeDlg::OnOK( wxCommandEvent &event )
{

}

void NodeDlg::OnInitDialog(wxInitDialogEvent& event)
{
    GetIntType()->Append("Unknown");
    GetIntType()->Append("Uncontrolled");
    GetIntType()->Append("All Signal Light(s)");
    GetIntType()->Append("All Stop Sign(s)");
    GetIntType()->Append("Signal Light(s)");
    GetIntType()->Append("Stop Sign(s)");
    GetIntType()->Append("(multiple)");

    GetBehavior()->Append("Uncontrolled");  // IT_NONE
    GetBehavior()->Append("Signal Light");  // IT_LIGHT
    GetBehavior()->Append("Stop Sign"); // IT_STOPSIGN

    // if we are editing multiple nodes at once, disable some of the
    // editing abilities
    if (!m_pNode)
    {
        GetRoadNum()->Enable(false);
        GetBehavior()->Enable(false);

        // Accumulate state
        int viz = -1;
        for (NodeEdit *n = m_pLayer->GetFirstNode(); n; n=n->GetNext())
        {
            if (!n->IsSelected())
                continue;
            if (viz == -1)
                viz = n->GetVisual();
            if (n->GetVisual() != viz)
                viz = MULTIPLE;
        }

        // Transfer state to control
        if (viz == MULTIPLE)
            GetIntType()->SetSelection(5);
        else
            GetIntType()->SetSelection(viz);
    }
    else
    {
        // single road
        wxString string;
        for (int i = 0; i < m_pNode->m_iRoads; i++)
        {
            string.Printf("%i", i);
            GetRoadNum()->Append(string);
        }
        GetRoadNum()->SetSelection(0);
        GetIntType()->SetSelection(m_pNode->GetVisual());
        int itype = m_pNode->GetIntersectType(0);
        GetBehavior()->SetSelection(itype);
    }
}

void NodeDlg::OnPaint(wxPaintEvent& event)
{
//  wxEvtHandler::OnPaint(event);
    wxPaintDC dc(this);
    OnDraw(dc);
}

static wxPoint buf[10];

//draw the node structure on the dialog box.
void NodeDlg::OnDraw(wxDC &dc)
{
    if (!m_pNode)
        return;

    vtScaledView *pView = GetMainFrame()->GetView();
    float fSaveScale = pView->GetScale();
    pView->SetScale(1.0f);

    wxPoint off;
    off.x = pView->sx(m_pNode->m_p.x);
    off.y = pView->sy(m_pNode->m_p.y);
    dc.SetDeviceOrigin(-off.x + 315, -off.y +125);
    dc.DrawLine(0, 0, 400, 400);
    m_pNode->Draw(&dc, pView);

    wxString string;
    for (int i = 0; i < m_pNode->m_iRoads; i++)
    {
        RoadEdit *pR = m_pNode->GetRoad(i);
        pR->Draw(&dc, pView);

        //we need to use the original node here because the roads point to it.
        DPoint2 close = m_pNode->find_adjacent_roadpoint2d(pR);
        DPoint2 vector = close - m_pNode->m_p;
        vector.Normalize();
        IPoint2 vec;

        vec.x = (int)(off.x + vector.x*20);
        vec.y = (int)(off.y - vector.y*20);

        //draw signal lights or stop signs as necessary.
        dc.SetLogicalFunction(wxCOPY);
        wxPen pen;

        switch (m_pNode->GetIntersectType(i))
        {
            case IT_STOPSIGN:
                pen.SetColour(128,0,0);
                dc.SetPen(pen);
                vec.x += 2;
                vec.y += 6;
                buf[0].x = vec.x; buf[0].y = vec.y;
                vec.x -= 4;
                buf[1].x = vec.x; buf[1].y = vec.y;
                vec.x -= 3;
                vec.y -= 3;
                buf[2].x = vec.x; buf[2].y = vec.y;
                vec.y -= 4;
                buf[3].x = vec.x; buf[3].y = vec.y;
                vec.x += 3;
                vec.y -= 3;
                buf[4].x = vec.x; buf[4].y = vec.y;
                vec.x += 4;
                buf[5].x = vec.x; buf[5].y = vec.y;
                vec.x += 3;
                vec.y += 3;
                buf[6].x = vec.x; buf[6].y = vec.y;
                vec.y += 4;
                buf[7].x = vec.x; buf[7].y = vec.y;
                vec.x -= 3;
                vec.y += 3;
                buf[8].x = vec.x; buf[8].y = vec.y;
                dc.DrawLines(9, buf);
                break;
            case IT_LIGHT:
                wxBrush brush;
                switch (m_pNode->GetLightStatus(i)) {
                    case LT_INVALID:
                        pen.SetColour(0,0,0);
                        brush.SetColour(0,0,0);
                        break;
                    case LT_RED:
                        pen.SetColour(128,0,0);
                        brush.SetColour(128,0,0);
                        break;
                    case LT_YELLOW:
                        pen.SetColour(0,128,128);
                        brush.SetColour(0,128,128);
                        break;
                    case LT_GREEN:
                        pen.SetColour(0,128,0);
                        brush.SetColour(0,128,0);
                        break;
                    default:
                //unrecognized
                        pen.SetColour(0,0,255);
                        brush.SetColour(0,0,255);
                }

                dc.SetPen(pen);
                dc.SetBrush(brush);
                wxRect box;
                int radius = 4;
                box.y = vec.y - radius;
                box.height = (radius << 1);
                box.x = vec.x - radius;
                box.width = (radius << 1);
                dc.DrawEllipse(box.x, box.y, box.width, box.height);
                break;
        }

        vec.x = (int)(off.x + vector.x*40);
        vec.y = (int)(off.y - vector.y*40);
        string.Printf("%i", i);
        //draw text labels
        dc.DrawText(string, vec.x-10, vec.y-10);
    }
    pView->SetScale(fSaveScale);
}
<commit_msg>fixed disabled OK button<commit_after>//
// Name:        NodeDlg.cpp
//
// Copyright (c) 2002 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
    #pragma implementation "NodeDlg.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
    #pragma hdrstop
#endif

#include "NodeDlg.h"
#include "RoadLayer.h"
#include "Frame.h"
#include "BuilderView.h"

#define MULTIPLE    5000

// WDR: class implementations

//----------------------------------------------------------------------------
// NodeDlg
//----------------------------------------------------------------------------

// WDR: event table for NodeDlg

BEGIN_EVENT_TABLE(NodeDlg,AutoDialog)
    EVT_PAINT(NodeDlg::OnPaint)
    EVT_LISTBOX( ID_INTTYPE, NodeDlg::OnIntType )
    EVT_LISTBOX( ID_ROADNUM, NodeDlg::OnRoadNum )
    EVT_LISTBOX( ID_BEHAVIOR, NodeDlg::OnBehavior )
END_EVENT_TABLE()

NodeDlg::NodeDlg( wxWindow *parent, wxWindowID id, const wxString &title,
    const wxPoint &position, const wxSize& size, long style ) :
    AutoDialog( parent, id, title, position, size, style )
{
    NodePropDialogFunc( this, TRUE );
}

void NodeDlg::SetNode(NodeEdit *pSingleNode, vtRoadLayer *pLayer)
{
    m_pNode = pSingleNode;
    m_pLayer = pLayer;
}

// WDR: handler implementations for NodeDlg

void NodeDlg::OnBehavior( wxCommandEvent &event )
{
	int sel = GetRoadNum()->GetSelection();
	//select new behavior and redraw it on the dialog.
	int itype = GetBehavior()->GetSelection();
	m_pNode->SetIntersectType(sel, (IntersectionType)itype );

	// this may have changed the VIT, so check
	m_pNode->DetermineVisualFromRoads();
    GetIntType()->SetSelection(m_pNode->GetVisual());

	Refresh();
}

void NodeDlg::OnRoadNum( wxCommandEvent &event )
{
	int sel = GetRoadNum()->GetSelection();
	//update what the behavior shows to match that of the road
	GetBehavior()->SetSelection(m_pNode->GetIntersectType(sel));
}

void NodeDlg::OnIntType( wxCommandEvent &event )
{
	//new node behavior
	VisualIntersectionType vitype;
	int sel = GetIntType()->GetSelection();
	if (sel == 0 || sel == 6)	// unknown or multiple not allowed
		return;

	vitype = (VisualIntersectionType) sel;

	if (m_pNode)
		ApplyVisualToNode(m_pNode, vitype);
	else
	{
        for (NodeEdit *n = m_pLayer->GetFirstNode(); n; n=n->GetNext())
        {
            if (!n->IsSelected())
                continue;
			ApplyVisualToNode(n, vitype);
		}
	}
	Refresh();
}

void NodeDlg::ApplyVisualToNode(NodeEdit *pNode, VisualIntersectionType vitype)
{
	int i;

	pNode->SetVisual(vitype);

	//overwrite all behaviors at the roads to match new assigned node behavior.
	switch (vitype)
	{
	case VIT_NONE:
		//make all intersections uncontrolled
		for (i = 0; i < m_pNode->m_iRoads; i++) {
			pNode->SetIntersectType(i, IT_NONE);
		}
		GetBehavior()->SetSelection(IT_NONE);
		break;
	case VIT_ALLSTOPS:
		//make all intersections stop signs
		for (i = 0; i < m_pNode->m_iRoads; i++) {
			pNode->SetIntersectType(i, IT_STOPSIGN);
		}
		GetBehavior()->SetSelection(IT_STOPSIGN);
		break;
	case VIT_ALLLIGHTS:
		//make all intersections lights
		for (i = 0; i < m_pNode->m_iRoads; i++) {
			pNode->SetIntersectType(i, IT_LIGHT);
		}
		GetBehavior()->SetSelection(IT_LIGHT);
		pNode->AdjustForLights();
		break;
	}
}

void NodeDlg::OnInitDialog(wxInitDialogEvent& event)
{
    GetIntType()->Append("Unknown");
    GetIntType()->Append("Uncontrolled");
    GetIntType()->Append("All Signal Light(s)");
    GetIntType()->Append("All Stop Sign(s)");
    GetIntType()->Append("Signal Light(s)");
    GetIntType()->Append("Stop Sign(s)");
    GetIntType()->Append("(multiple)");

    GetBehavior()->Append("Uncontrolled");  // IT_NONE
    GetBehavior()->Append("Signal Light");  // IT_LIGHT
    GetBehavior()->Append("Stop Sign"); // IT_STOPSIGN

    // if we are editing multiple nodes at once, disable some of the
    // editing abilities
    if (!m_pNode)
    {
        GetRoadNum()->Enable(false);
        GetBehavior()->Enable(false);

        // Accumulate state
        int viz = -1;
        for (NodeEdit *n = m_pLayer->GetFirstNode(); n; n=n->GetNext())
        {
            if (!n->IsSelected())
                continue;
            if (viz == -1)
                viz = n->GetVisual();
            if (n->GetVisual() != viz)
                viz = MULTIPLE;
        }

        // Transfer state to control
        if (viz == MULTIPLE)
            GetIntType()->SetSelection(5);
        else
            GetIntType()->SetSelection(viz);
    }
    else
    {
        // single road
        wxString string;
        for (int i = 0; i < m_pNode->m_iRoads; i++)
        {
            string.Printf("%i", i);
            GetRoadNum()->Append(string);
        }
        GetRoadNum()->SetSelection(0);
        GetIntType()->SetSelection(m_pNode->GetVisual());
        int itype = m_pNode->GetIntersectType(0);
        GetBehavior()->SetSelection(itype);
    }
}

void NodeDlg::OnPaint(wxPaintEvent& event)
{
//  wxEvtHandler::OnPaint(event);
    wxPaintDC dc(this);
    OnDraw(dc);
}

static wxPoint buf[10];

//draw the node structure on the dialog box.
void NodeDlg::OnDraw(wxDC &dc)
{
    if (!m_pNode)
        return;

    vtScaledView *pView = GetMainFrame()->GetView();
    float fSaveScale = pView->GetScale();
    pView->SetScale(1.0f);

    wxPoint off;
    off.x = pView->sx(m_pNode->m_p.x);
    off.y = pView->sy(m_pNode->m_p.y);
    dc.SetDeviceOrigin(-off.x + 315, -off.y +125);
    dc.DrawLine(0, 0, 400, 400);
    m_pNode->Draw(&dc, pView);

    wxString string;
    for (int i = 0; i < m_pNode->m_iRoads; i++)
    {
        RoadEdit *pR = m_pNode->GetRoad(i);
        pR->Draw(&dc, pView);

        //we need to use the original node here because the roads point to it.
        DPoint2 close = m_pNode->find_adjacent_roadpoint2d(pR);
        DPoint2 vector = close - m_pNode->m_p;
        vector.Normalize();
        IPoint2 vec;

        vec.x = (int)(off.x + vector.x*20);
        vec.y = (int)(off.y - vector.y*20);

        //draw signal lights or stop signs as necessary.
        dc.SetLogicalFunction(wxCOPY);
        wxPen pen;

        switch (m_pNode->GetIntersectType(i))
        {
            case IT_STOPSIGN:
                pen.SetColour(128,0,0);
                dc.SetPen(pen);
                vec.x += 2;
                vec.y += 6;
                buf[0].x = vec.x; buf[0].y = vec.y;
                vec.x -= 4;
                buf[1].x = vec.x; buf[1].y = vec.y;
                vec.x -= 3;
                vec.y -= 3;
                buf[2].x = vec.x; buf[2].y = vec.y;
                vec.y -= 4;
                buf[3].x = vec.x; buf[3].y = vec.y;
                vec.x += 3;
                vec.y -= 3;
                buf[4].x = vec.x; buf[4].y = vec.y;
                vec.x += 4;
                buf[5].x = vec.x; buf[5].y = vec.y;
                vec.x += 3;
                vec.y += 3;
                buf[6].x = vec.x; buf[6].y = vec.y;
                vec.y += 4;
                buf[7].x = vec.x; buf[7].y = vec.y;
                vec.x -= 3;
                vec.y += 3;
                buf[8].x = vec.x; buf[8].y = vec.y;
                dc.DrawLines(9, buf);
                break;
            case IT_LIGHT:
                wxBrush brush;
                switch (m_pNode->GetLightStatus(i)) {
                    case LT_INVALID:
                        pen.SetColour(0,0,0);
                        brush.SetColour(0,0,0);
                        break;
                    case LT_RED:
                        pen.SetColour(128,0,0);
                        brush.SetColour(128,0,0);
                        break;
                    case LT_YELLOW:
                        pen.SetColour(0,128,128);
                        brush.SetColour(0,128,128);
                        break;
                    case LT_GREEN:
                        pen.SetColour(0,128,0);
                        brush.SetColour(0,128,0);
                        break;
                    default:
                //unrecognized
                        pen.SetColour(0,0,255);
                        brush.SetColour(0,0,255);
                }

                dc.SetPen(pen);
                dc.SetBrush(brush);
                wxRect box;
                int radius = 4;
                box.y = vec.y - radius;
                box.height = (radius << 1);
                box.x = vec.x - radius;
                box.width = (radius << 1);
                dc.DrawEllipse(box.x, box.y, box.width, box.height);
                break;
        }

        vec.x = (int)(off.x + vector.x*40);
        vec.y = (int)(off.y - vector.y*40);
        string.Printf("%i", i);
        //draw text labels
        dc.DrawText(string, vec.x-10, vec.y-10);
    }
    pView->SetScale(fSaveScale);
}
<|endoftext|>